在相对定位的div内绝对定位图像 [英] Absolutely positioning images inside relatively positioned div

查看:167
本文介绍了在相对定位的div内绝对定位图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过几个与这个问题相关的文章,但仍然无法让以下内容正常运作:

I've seen several posts related to this issue, but still can't get the following to work:

.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 ,具体来说:


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

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的高度。我知道浮动一个图像左,而另一个图像右,并设置overflow:auto容器div将工作,但我想我希望不必去那条路线,因为我喜欢绝对定位技术在一个相对div。

The issue is that the container div has no height. I'd really like to not have to specify the height of the container div. I know that floating the one image left, and the other image right, and setting overflow: auto on the container div will work, but I guess I was hoping to not have to go that route since I like the technique of absolute positioning inside a relative div.

这是否可能?

推荐答案

父容器动态调整到你绝对定位的孩子,因为孩子在流程之外。

There is no natural way for the parent container to resize dynamically to your absolutely positioned children because the children are outside of the flow.

做你正在描述的最好的方法是使用浮动,清除方法:

The best way of doing what you are describing is to use floats, and a clearing method:

<style type="text/css" media="screen">
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 */
</style>
<body>
  <div class="container clearfix">
    <div class="left">
      Left
    </div>
    <div class="right">
      Right
    </div>
  </div>
</body>

如果你坚持做绝对定位并且需要父容器匹配子代的高度,将必须诉诸于javascript。

If you insist on doing absolute positioning and need the parent container to match the height of the children, you will have to resort to javascript.

这篇关于在相对定位的div内绝对定位图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆