这个div崩溃的例子是什么?
What is this div collapse an example of?
Here is the jsfiddle 来说明我的问题。
我有一个没有高度的浮动 div (.card
)。它包含带有图像的嵌套 div (.image
)。该图像使 .card
的边界框扩展以包裹图像。
但是,当我将第二个 div (.text
) 作为 .image
的同级嵌套在 .card
内并使用否定 margin-top 定位 .text
在图像顶部,图像不再设法扩展 .card
的 bounding-box 以匹配图像底部。 .card
的 bottom-boundary 反而爬升并跟随 .text
的底部边界。
当 .text
存在时,为什么图像不再成功扩展其 grand-parent?
<div class="card">
<div class="image">
<img src="https://dl.dropboxusercontent.com/u/55892413/jsfiddle/image.jpg" width="200px"></div>
</div>
<div class="card">
<div class="image">
<img src="https://dl.dropboxusercontent.com/u/55892413/jsfiddle/image.jpg" width="200px"></div>
<div class="text"></div>
</div>
img {
display: block;
}
.card {
border: 1px solid black; //shows where the bounding-box of this div is
width: 200px;
position: relative;
float: left;
}
.text {
width: 100px;
height: 100px;
background-color: red;
margin-top: -120px;
position: relative;
}
如果你的观点没有错,那么你就错过了 position:absolute。
记住,只有当父元素 div 是相对的而内部元素是绝对的时,你才能固定内部元素的位置。
已更新
出现此问题是因为您尝试在 .card(parent) 中使用 .txt(child) 且位置相对,但方式错误。请记住,每当您使用位置时,父项应该是相对的,子项将是绝对的,因此子项将在父容器内移动而不会中断流程(在您的情况下,它会影响父项 div 并打破边界)所以要结束这个问题在 child 上使用 position:absolute 然后你可以轻松使用 .txt class。
只需在 .text class 中更改 position: relative;
to position: absolute;
即可。
见here
Here is the jsfiddle 来说明我的问题。
我有一个没有高度的浮动 div (.card
)。它包含带有图像的嵌套 div (.image
)。该图像使 .card
的边界框扩展以包裹图像。
但是,当我将第二个 div (.text
) 作为 .image
的同级嵌套在 .card
内并使用否定 margin-top 定位 .text
在图像顶部,图像不再设法扩展 .card
的 bounding-box 以匹配图像底部。 .card
的 bottom-boundary 反而爬升并跟随 .text
的底部边界。
当 .text
存在时,为什么图像不再成功扩展其 grand-parent?
<div class="card">
<div class="image">
<img src="https://dl.dropboxusercontent.com/u/55892413/jsfiddle/image.jpg" width="200px"></div>
</div>
<div class="card">
<div class="image">
<img src="https://dl.dropboxusercontent.com/u/55892413/jsfiddle/image.jpg" width="200px"></div>
<div class="text"></div>
</div>
img {
display: block;
}
.card {
border: 1px solid black; //shows where the bounding-box of this div is
width: 200px;
position: relative;
float: left;
}
.text {
width: 100px;
height: 100px;
background-color: red;
margin-top: -120px;
position: relative;
}
如果你的观点没有错,那么你就错过了 position:absolute。
记住,只有当父元素 div 是相对的而内部元素是绝对的时,你才能固定内部元素的位置。
已更新
出现此问题是因为您尝试在 .card(parent) 中使用 .txt(child) 且位置相对,但方式错误。请记住,每当您使用位置时,父项应该是相对的,子项将是绝对的,因此子项将在父容器内移动而不会中断流程(在您的情况下,它会影响父项 div 并打破边界)所以要结束这个问题在 child 上使用 position:absolute 然后你可以轻松使用 .txt class。
只需在 .text class 中更改 position: relative;
to position: absolute;
即可。
见here