Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div has no height when there is img inside it

Tags:

html

css

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;
   }
like image 654
Mike Boory Avatar asked Sep 18 '13 15:09

Mike Boory


People also ask

Why does my div have no height?

The reason why the height or the containers is 0 is because you are floating all the content inside them and floated elements don't expand the height (or width) of their parents. As you are floating all elents in row it has 0 height and therfore so has .

Should I put IMG in div?

The right way: <img> if image is relevant, <div> with background if image is eye-candy only. If image size is variable and important, you should use <img> .

How do I keep an image inside a div?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

How do I display an image in a div?

This can be done by enclosing the image and text in an HTML “div”. Then make the position of div “relative” and that of text “absolute”. The absolute elements are positioned relative to their parent (div). The top, right, bottom, and left properties of these elements specify their location from the parent.


1 Answers

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

like image 137
Huangism Avatar answered Oct 18 '22 01:10

Huangism