Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS floats and block elements

I have an annoying CSS layout problem. I'm trying to float images on a particular page:

img {
  float: left;
}

I think make sure my headings don't start indented with:

h3 {
  clear: left;
}

It all works fine except for some of the images that have lists (or any block element) floating past them (or not as the case is). The reason for this is actually clear in the CSS spec: block elements don't flow. Line/inline elements do.

This is a real problem for lists however. Is there any way around it in a fairly generic and compatible way?

like image 469
cletus Avatar asked Nov 24 '25 06:11

cletus


1 Answers

Here's what I always do to make sure the float is always cleared:

  1. Add the following to the CSS:

    .clearfix:after {
        content: ".";
        display: block;
        clear: both;
        visibility: hidden;
        line-height: 0;
        height: 0;
    }
    
    .clearfix {
        display: inline-block;
    }
    
    html[xmlns] .clearfix {
        display: block;
    }
    
    `*` html .clearfix {
        height: 1%;
    }
    

    You can also find this code here.

  2. Mark every parent of the element that's floated with class clearfix.

like image 118
Kon Avatar answered Nov 26 '25 21:11

Kon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!