【CSS】clearfixについて


概要

floatプロパティによって浮いた要素の回り込みを解除できる(バリアを張るイメージ)

具体例

  <div class="clearfix"> 
    <div class="box1"></div> 
    <div class="box2"></div> 
  </div> 
  <div class="box3"></div>
.clearfix::after{ 
  content: ""; 
  display: block; 
  clear: both; 
} 
.box1{ 
  background-color: red; 
  width: 200px; 
  height: 200px; 
  float: left; 
} 
.box2{ 
  background-color: green; 
  width: 200px; 
  height: 200px; 
  float: left; 
} 
.box3{ 
  background-color: yellow; 
  width: 200px; 
  height: 200px; 
}

実行

yellowがredの下に回り込むのを解除している

.clearfix::after
clearfixというクラス名を付けた要素の直後

content:"";
contentプロパティで任意の文字を挿入

display: block;
clearfixを付けた要素の直後に要素を作る

clear: both;
float解除

参考