【问题标题】:CSS position relative and absoluteCSS位置相对和绝对
【发布时间】:2017-04-29 16:08:04
【问题描述】:

我是网络开发的新手。我对元素的定位有一些疑问。

当我运行以下代码时,黑色背景元素位于红色背景元素内。

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<div style="position: absolute;left:100px;top: 100px;height:600px;background-color: yellow;width: 600px;">
		<div style="position:relative;left:100px;top:100px;height:200px;width:500px;background-color: red;">
		</div>
		<div style="position:relative;left:100px;top:50px;height:10px;width:10px;background-color: black;">
		</div>
	</div>
</body>
</html>

但是,如果我将红色矩形的位置设置为绝对位置,则黑色矩形会移动到正确的位置,从而保持其父级(黄色矩形)的正确左侧和顶部。谁能告诉我为什么会这样?即使红色矩形的位置是相对的,如何使黑色矩形从其父(黄色矩形)正确定位。

谢谢

【问题讨论】:

    标签: html css css-position


    【解决方案1】:

    relative 定位将元素保留在页面上,因此它们的位置会受到其他staticrelative 定位元素的影响。如果您希望黑框相对于黄框定位,您需要将黑框设为position: absoluteabsolutely 定位的元素将相对于它最近的非static 定位的祖先定位。

    <!DOCTYPE html>
    <html>
    
    <head>
      <title></title>
    </head>
    
    <body>
      <div style="position: absolute;left:100px;top: 100px;height:600px;background-color: yellow;width: 600px;">
        <div style="position:relative;left:100px;top:100px;height:200px;width:500px;background-color: red;">
        </div>
        <div style="position:absolute;left:100px;top:50px;height:10px;width:10px;background-color: black;">
        </div>
      </div>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      相关资源
      最近更新 更多