cssclearfix

How to use "clearfix" css in nested blocks?


I'd found, that css "clearfix" example not work properly when there are nested float:left blocks.

Here is an example:

.left {
  float: left;
  width: 100px;
  height: 200px;
  background: green;
}

.right {
  margin-left: 100px;
  background: yellow;
}

.clearfix:after {
  content: ' ';
  display: table;
  clear: both;
}

ul.clearfix {
  padding: 10px;
}

.clearfix li {
  float: left;
  list-style: none;
  border: 1px solid red;
}
<div class="left">
  Image
</div>
<div class="right">
  <ul class="clearfix">
    <li>A</li>
    <li>B</li>
    <li>C</li>
  </ul>
  <p>Some description</p>
</div>

It shows, that text "some text" appears quite under "left" block. While there presents huge space after list of elements with "clearfix" css. Any ideas to fix it?


Solution

  • In this particular case you can make the p inline-block and you will not need clearfix (at least inside the right element). You may need to clear after the right element if you will have more content.

    .left {
      float: left;
      width: 100px;
      height: 200px;
      background: green;
    }
    
    .right {
      margin-left: 100px;
      background: yellow;
    }
    
    ul.clearfix {
      padding: 10px;
    }
    
    .clearfix li {
      float: left;
      list-style: none;
      border: 1px solid red;
    }
    p {
      display:inline-block;
      width:100%;
    }
    <div class="left">
      Image
    </div>
    <div class="right">
      <ul class="clearfix">
        <li>A</li>
        <li>B</li>
        <li>C</li>
      </ul>
      <p>Some description</p>
    </div>