绝对将图像定位在相对定位的div内

Jus*_*ler 12 html css css-position

我看过几个与此问题相关的帖子,但仍然无法使用以下内容:

.container {
  position: relative;
  width: 100%;
}

.left {
  position: absolute;
  left: 0px;
}

.right {
  position: absolute;
  right: 0px;
}
Run Code Online (Sandbox Code Playgroud)

根据http://www.w3schools.com/css/css_positioning.asp,具体说明:

绝对位置元素相对于具有静态位置的第一父元素定位.如果未找到此类元素,则包含块为<html>

问题是容器div没有高度.我真的不想指定容器div的高度.我知道向左浮动一个图像,向右浮动另一个图像,并设置溢出:容器div上的auto会起作用,但我想我希望不必去那条路,因为我喜欢绝对定位的技术相对div.

这可能吗?

Xac*_*o01 4

父容器没有自然的方法可以根据绝对定位的子容器动态调整大小,因为子容器位于流程之外。

执行您所描述的操作的最佳方法是使用浮动和清除方法:

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 */
Run Code Online (Sandbox Code Playgroud)
<body>
  <div class="container clearfix">
    <div class="left">
      Left
    </div>
    <div class="right">
      Right
    </div>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

如果你坚持做绝对定位并且需要父容器匹配子容器的高度,你将不得不求助于javascript。