user1310420
user1310420

Reputation:

CSS keep height when image when floating

I have a div that has a photo that has the float: left attribute and text is right next to it, like this:

<div id='1'>
 <img src='img.jpg' width='50%' style='float:left;' />
  This is text next to it<br/><br/>More text
</div>

I don't know the dimensions of the image, or the height of the text, but the text is often shorter than the image, causing the div to be shorter than the image (which looks really bad). Is there any way I can fix this?

Upvotes: 0

Views: 1071

Answers (2)

I think the optimal solution is to add new div at the end and clear everything with it. like this:

CSS in first case:

#1:after{
    content: "";
    height: 0;
    clear: both;
    display: block; 
}

Second case: HTML:

<div id='1'>
 <img src='img.jpg' width='50%' style='float:left;'>
  This is text next to it<br><br>More text
  <div class="cl"></div>
</div>

CSS:

.cl {
clear: both;
}

or if you want to run in the oldest versions of IE you can add:

.cl { 
font-size: 0; 
line-height: 0; 
text-indent: -4000px; 
clear: both;
}

Upvotes: 0

Mateusz Rogulski
Mateusz Rogulski

Reputation: 7445

Just add overflow: hidden; to your first div.

Addicionally ids and classes in CSS can not start from numbers.

Upvotes: 2

Related Questions