我看过几个与此问题相关的帖子,但仍然无法使以下内容正常工作:
.container {
position: relative;
width: 100%;
}
.left {
position: absolute;
left: 0px;
}
.right {
position: absolute;
right: 0px;
}
<html>
<body>
<div class="container">
<img src="..." class="left" />
<img src="..." class="right" />
</div>
</body>
</html>
根据 http://www.w3schools.com/css/css_positioning.asp ,特别是那一行:
An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html>
问题是容器 div 没有高度。我真的不想指定容器 div 的高度。我知道将一张图片向左浮动,将另一张图片向右浮动,并在容器 div 上设置 overflow: auto 会起作用,但我想我希望不必走那条路,因为我喜欢在 a 内进行绝对定位的技术相对分区
这可能吗?
最佳答案
父容器没有自然的方法可以根据绝对定位的子容器动态调整大小,因为子容器在流之外。
做你所描述的最好的方法是使用 float 和清除方法:
body {
padding: 20px;
}
.container {
position: relative;
width: 100%;
background: yellow;
}
.left {
float: left;
background: red;
width: 100px;
height: 200px;
}
.right {
float: right;
background: blue;
width: 100px;
height: 200px;
}
/* Use the clearfix technique: http://www.yuiblog.com/blog/2010/09/27/clearfix-reloaded-
overflowhidden-demystified/ */
.clearfix:before,
.clearfix:after {
content: ".";
display: block;
height: 0;
overflow: hidden;
}
.clearfix:after {
clear: both;
}
.clearfix {
zoom: 1;
}
/* IE < 8 */
<body>
<div class="container clearfix">
<div class="left">
Left
</div>
<div class="right">
Right
</div>
</div>
</body>
如果你非要做绝对定位,需要父容器匹配子容器的高度,那只能求助于javascript。
关于html - 在相对定位的 div 中绝对定位图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5546288/