LoginSignup
0
0

More than 5 years have passed since last update.

ブロック要素を横並びにした時の面倒なバグは、clearfixで解消しよう。

Last updated at Posted at 2016-11-04

レイアウトにおいて要素の横並びは非常に大切。

メインコンテンツとサブコンテンツなど、どのサイトにおいても横並びが絶対使われている。
ブロック要素の横並びには、floatを使うんだけど、このfloatが若干面倒くさい。

floatの面倒臭さとは

この面倒臭さを知るためには、まずhtml, cssにおける親要素の高さの決定する仕組みを知る必要がある。

親要素の高さは、子要素の高さの合計になる。

例えば

index.html
    <div class="contents">
      <div class="upper_content"> 
      </div>
      <div class="lower_content">
      </div>
    </div>


style.css
.contents{
  width: 960px;
  background-color: red;
}
.upper_content{
  height: 400px;
  width: 640px;
  background-color: green;
}

.lower_content{
  height: 370px;
  width: 320px;
  background-color: yellow;
}

では、親要素であるcontetsのheightは、子要素であるupper_contentのheight 400pxとlower_contentのheight 370pxの合計値770pxとなる。

次に、この前提でfloatの面倒臭さだ。

floatをかけた要素は、浮いている状態になり、高さが認識されなくなる。
もし子要素であるupper_contentとlower_contentを横並びにしたい場合、それぞれにfloatをかける。すると親要素であるcontentsは、子要素の高さを認識することができなくなるので、高さがなくなってしまうのだ!

それを解決するclearfix:after

さて、そんな面倒なfloat問題をどう解決すればいいのか。

いろいろ方法はあるが、clearfixを作製することが楽なんじゃないかと思っている。

style.css
(一部抜粋、upper_contentをleft_contentに、lower_contentをright_contentに名称変更
)

style.css
.contents{
  width: 960px;
  background-color: red;
}

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

.left_content{
  height: 400px;
  width: 640px;
  background-color: green;
  float: left;
}

.right_content{
  height: 370px;
  width: 320px;
  background-color: yellow;
  float: left;
}

index.html
    <div class="contents clearfix">
      <div class="left_content">
      </div>
      <div class="right_content">
      </div>
    </div>

このように、横並びをさせる子要素にfloat:leftを、そして親要素に対してclearfixをあててあげることによって、高さが検出されるようになる。

ちなみにafterは、疑似要素と言われるもので親要素の最下部に新たな要素を追加する、というものらしい。(ここらへんはあまり詳しくないので詳細を知りたい方はググってくださいw)

で、clearfix内のプロパティをそれぞれ簡単に触れると

.clearfix:after{
  content: "";      /* 文字列を突っ込むというもの。何も入れないので""でOK! */
  display: block;   /* block要素で表示させるよ!というもの               */
  clear: both;      /* 一番重要。これで回り込みのバグを消している。        */
}

てな感じ。

まとめると、「子要素にfloatをかけて、親要素にclear fixを当てる」。

以上。

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