html - 在相对定位的 div 中绝对定位图像

标签 html css css-position

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

.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/

相关文章:

html - 是否可以使输入类型数字适合其显示的数字宽度?

javascript - 第一个函数调用 html 按钮 onclick,但不调用任何其他函数

html - 如何在绝对位置父级上设置子级高度

html - 如何使用 Nokogiri 解析 TABLE 文本?

html - CSS 计数器 - 递增深度嵌套列表

html - 最小/最大宽度在浏览器中以相反的顺序显示

php - 在之后打印 mysql 结果 10 x 10 php css 分页符

php - 重命名 html、php 和 css 文件中的文本

css - 为什么 Firefox 对顶部偏移的解释与 Chrome、Safari 和 IE 不同?

html - 定位问题