0
0

More than 1 year has passed since last update.

floatとclearfixの使い方

Posted at

floatとclearfixの違い

ある要素の中で横並びのレイアウトを実現するために、floatをかけた要素の高さを親要素が認識しなくなることで、表示が崩れる場合がある。

floatプロパティとは

要素に'right'や'left'といったように、値を設定すると要素を右・左寄せすることができる
また、floatは'浮く'という意味
例) float: 'left'; (左寄せ)

clearixプロパティとは

floatプロパティに'right'や'left'を設定することで、要素が右寄せ左寄せになった要素に対して、回り込みを解除するプロパティ

floatで要素を横並びにする

index.html
<body>
    <div class="left"></div>
    <div class="right"></div>
    <div class="bottom"></div>
</body>
style.css
.left {
  float: left;
  width: 100px;
  height: 100px;
  background-color: yellow;
}
.right {
  float: left;
  width: 200px;
  height: 200px;
  background-color: red;
}

.bottom {
  float: left;
  width: 300px;
  height: 300px;
  background-color: green;
}

以下のような表示になる(黄色、赤、緑が横並びになる)

HTML ボックス.jpg

ここで、緑だけ'float: left;'を解除すると

HTML float解除.jpg

このように、黄色と赤色の下に緑色が回り込んでしまう。
この回り込みを解除して、黄色と赤色の下に表示するには、clearfixを使う。

clearfixで回り込みを解除する

index.html
<body>
  <div class="clearfix">
    <div class="left"></div>
    <div class="right"></div>
  </div>
  <div class="bottom"></div>
</body>
style.css
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}
.left {
  float: left;
  width: 100px;
  height: 100px;
  background-color: yellow;
}
.right {
  float: left;
  width: 200px;
  height: 200px;
  background-color: red;
}
.bottom {
  width: 300px;
  height: 300px;
  background-color: green;
}

上記のように、clearfixクラスを追加し、cssを記述すると下の画像のように、黄色と赤色の下に緑色がずれ込む。

HTML clearfix.jpg

clearfixクラス

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

::after
=> 擬似要素。選択した要素の最後に子要素が作られる

content: "";
=> ::beforeまたは::afterを指定する場合、必ずcontentを指定する必要があり,任意の文字列を指定することができる。
テキストや記号を擬似要素として挿入したい場合は、content内に記述し、要素や画像は、contentを空にする。

display: block;
=> コンテンツをまとめるブロック要素を指定

clear: both;
=> floatを解除する

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0