CSSでfloatを使うとよく、高さを指定する部分で謎にハマってしまうことがあります。
そもそもこういう風にfloatは使わないよ、と言われてしまいそうですが、なんとかfloatで表現したい時もあります。
そこで以下のように、floatとheight,topの組み合わせのサンプルを用意しました。一目瞭然です。
<style> ul,li{ list-style: none; margin: 0; } .demo_ul1{ clear: both; background-color: #CCC; width: 200px; } .demo_ul1 li:nth-of-type(1){ float: left; background-color: #FF0; } .demo_ul1 li:nth-of-type(2){ float: left; background-color: #F0F; } .demo_ul1 li:nth-of-type(3){ float: left; background-color: #0FF; } .demo_ul1 li:nth-of-type(4){ float: left; background-color: #00F; color: #FFF; height:50%; } </style> <ul class="demo_ul1"> <li>A<br>A</li> <li>B<br>B<br>B</li> <li>C<br>C<br>C<br>C</li> <li>height:50%;</li> </ul>
- A
A - B
B
B - C
C
C
C - height:50%;
4つ目のliの高さを親要素ulの半分の高さにしたい場合、上記ではうまくいきません。
<style> .demo_ul2{ clear: both; background-color: #CCC; height: 300px; width: 200px; } .demo_ul2 li:nth-of-type(1){ float: left; background-color: #FF0; } .demo_ul2 li:nth-of-type(2){ float: left; background-color: #F0F; } .demo_ul2 li:nth-of-type(3){ float: left; background-color: #0FF; } .demo_ul2 li:nth-of-type(4){ float: left; background-color: #00F; color: #FFF; height:50%; } </style>
- A
A - B
B
B - C
C
C
C - height:50%;
やりたいことはおそらく上記。親要素の高さを指定してあげないと、子要素のheightは聞きません。
<style> .demo_ul3{ clear: both; background-color: #CCC; width: 200px; } .demo_ul3 li:nth-of-type(1){ float: left; background-color: #FF0; } .demo_ul3 li:nth-of-type(2){ float: left; background-color: #F0F; } .demo_ul3 li:nth-of-type(3){ float: left; background-color: #0FF; } .demo_ul3 li:nth-of-type(4){ float: left; background-color: #00F; color: #FFF; top:50%; } </style>
- A
A - B
B
B - C
C
C
C - top:50%;
上記は親要素の高さの中間に4つ目のliを配置した場合の失敗例が上記です。
<style> .demo_ul4{ clear: both; background-color: #CCC; height: 300px; width: 200px; position: absolute; clear: both; } .demo_ul4 li:nth-of-type(1){ float: left; background-color: #FF0; } .demo_ul4 li:nth-of-type(2){ float: left; background-color: #F0F; } .demo_ul4 li:nth-of-type(3){ float: left; background-color: #0FF; } .demo_ul4 li:nth-of-type(4){ float: left; background-color: #00F; color: #FFF; top:50%; position: relative; } </style>
- A
A - B
B
B - C
C
C
C - top:50%;
親要素の高さとポジションを指定してあげると、中間に配置することができます。