Absolutely positioning images inside relatively positioned div

半城伤御伤魂 提交于 2019-12-21 03:43:32

问题


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>

According to http://www.w3schools.com/css/css_positioning.asp, specifically the line that says:

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>

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.

Is this possible?


回答1:


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:

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>

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.



来源:https://stackoverflow.com/questions/5546288/absolutely-positioning-images-inside-relatively-positioned-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!