我的问题是为什么更改div.container中的填充会影响div.blueBox?由于blueBox定位设置为绝对值,因此它将从正常流量中取出,并且应该与元素相关联。
HTML:
<body>
<div class="container">
<div class="box blueBox"></div>
</div>
<div class="box greenBox"></div>
<h1>Understanding CSS Positioning</h1>
<p><em>Absolute positioning</em> takes an element out of document flow, meaning the browser acts as if the element has no width and height, and the other elements on the page move up as if it was never there. The position of the element is then fixed relative to the top level container, or the closest parent with a set positioning.</p>
</body>
CSS:
body {
background-color: #1f1f1f;
height: 2000px;
color: #bfbfbf;
}
h1 {
font-weight: normal;
}
em {
color: #dd740b;
}
.box {
width: 100px;
height: 100px;
margin-bottom: 10px;
}
.blueBox {
background: #627da0;
position: absolute;
}
.greenBox {
background: #5b8054;
}
.container {
background: rgba(0,0,0,.4);
padding: 10px;
}
答案 0 :(得分:1)
添加绝对位置时,您需要定义:
position: absolute;
left: 0;
top: 0;
答案 1 :(得分:1)
绝对定位相对于其最近的祖先放置一个元素,该祖先也具有静态以外的定位。
如果您希望.blueBox
相对于身体定位,请设置顶部和左侧值:
body {
background-color: #1f1f1f;
color: #bfbfbf;
}
.box {
width: 100px;
height: 100px;
margin-bottom: 10px;
}
.blueBox {
background: #627da0;
position: absolute;
top: 0;
left: 0;
}
.container {
background: pink;
padding: 10px;
}
<body>
<div class="container">
<div class="box blueBox"></div>
</div>
<div class="box greenBox"></div>
<h1>Understanding CSS Positioning</h1>
<p><em>Absolute positioning</em> takes an element out of document flow, meaning the browser acts as if the element has no width and height, and the other elements on the page move up as if it was never there. The position of the element is then fixed relative
to the top level container, or the closest parent with a set positioning.</p>
</body>
如果您希望它定位于.container
,则需要定位.container
:
body {
background-color: #1f1f1f;
color: #bfbfbf;
}
.box {
width: 100px;
height: 100px;
margin-bottom: 10px;
}
.blueBox {
background: #627da0;
position: absolute;
top: 0;
left: 0;
}
.container {
background: pink;
padding: 10px;
position: relative;
}
<body>
<div class="container">
<div class="box blueBox"></div>
</div>
<div class="box greenBox"></div>
<h1>Understanding CSS Positioning</h1>
<p><em>Absolute positioning</em> takes an element out of document flow, meaning the browser acts as if the element has no width and height, and the other elements on the page move up as if it was never there. The position of the element is then fixed relative
to the top level container, or the closest parent with a set positioning.</p>
</body>
答案 2 :(得分:0)
您需要定义其余的position
元素。例如top
或left
等
您可能也想要relative
而不是absolute
。
.blueBox {
background: #627da0;
position: absolute;
top: 0;
left: 0;
}