【问题标题】:Absolutely positioning images inside relatively positioned div在相对定位的 div 内绝对定位图像
【发布时间】:2011-07-29 14:41:17
【问题描述】:

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

.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,特别是上面写着的那一行:

绝对位置元素相对于第一个具有非静态位置的父元素定位。如果没有找到这样的元素,则包含块是

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

这可能吗?

【问题讨论】:

  • 我认为@Xactor 是对的。实现您所描述的最佳方法是使用浮点数和清除方法。
  • 如果您有一个相对的父级,为什么子图像的绝对位置不起作用?我不明白您所说的“问题是容器 div 没有高度”是什么意思。

标签: html css css-position


【解决方案1】:

父容器没有自然的方式来动态调整绝对定位的子容器的大小,因为子容器在流程之外。

做你所描述的最好的方法是使用浮点数和清除方法:

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了。

【讨论】:

  • 非常感谢。我想我会用这种方法。伙计,虽然关于 clearfix 方法的阅读量很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 2015-07-28
  • 2018-12-05
  • 1970-01-01
相关资源
最近更新 更多