10

I have a div[div1] that is surrounding other elements. Inside the elements I have an image that is positioned absolute. Div1 and the elements have float left on them and are showing no height. Is there a way to have this so the main overall div1 has a height so other elements like footers can be floated below it.

HTML

<div class="div1">
  <div> <img src="image1.jpg" /> </div>
  <div> <img src="image2.jpg" /> </div>
  <div> <img src="image3.jpg" /> </div>
</div>

CSS

.div1{
   width:100%;
   height:auto;
   overflow:auto;
   float:left;
   }
.div1 div{
   width:100%;
   height:auto;
   overflow:auto;
   float:left;
   }
.div1 div img{
   width:100%;
   height:auto;
   position:absolute;
   display:block;
   float:left;
   }
4

2 回答 2

15

If you want div1 to have a height, then remove the position absolute from the images

.div1 div img{
   width: 100%;
   display: block;
   float: left;
}

Since all your elements are floating, the div1 will have a height. Your images were positioned absolutely so it is taken out of the content flow. This is the same as your divs not having any content inside of it, so you don't get a height.

http://jsfiddle.net/QDYYw/3/

Update :

Make the first image not positioned absolutely and the rest can be positioned absolutely, so they still have the stacking effect you want and the container will have a height since 1 of your images is in the content flow.

<div class="div1">
  <img src="image1.jpg" />
  <img src="image2.jpg" />
  <img src="image3.jpg" />
</div>

CSS

.div1 img:first-child {
   position: static;
}

see http://jsfiddle.net/QDYYw/4/ for full code

于 2013-09-18T15:44:05.877 回答
0

That is because of the floats. A div is a block element, which always is 100%, so width: 100% is not needed. Also remove the display:block (div is block by default) and of you dont have a specific reason for the absolute, remove that too. And offcourse remove the floats.

If you want to keep everything, just give your divs position:relative;, absolute is always relative to the first relative element it finds

于 2013-09-18T15:29:53.170 回答