Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolutely positioning images inside relatively positioned 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>

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?

like image 459
Justin Miller Avatar asked Apr 05 '11 01:04

Justin Miller


1 Answers

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.

like image 115
Xacto01 Avatar answered Oct 05 '22 10:10

Xacto01