縦中央揃え

CSS入門

 
 
まずは例を見てみましょう。

<style>
.component-ex:after{ clear: both; display: block; content: ” }
.component-ex .label {
 float: left;
 width: 300px;
 height: 50px;
 font-size: 16px;
 text-align: center;
 background-color: #ccc;
}
.component-ex .plus-btn {
 float: left;
 width: 50px;
 height: 50px;
 font-size: 24px;
 text-align: center;
 background-color: #2c77f6;
 color: white;
}
</style>
<div class=”component-ex”>
 <div class=”label”>Test Component</div>
 <div class=”plus-btn”>+</div>
</div>

出力結果

Test Component
+

 
横の配置は、floatとclearを使えば簡単に構成できました。横中央揃えもtext-align属性を使えば簡単です。
では、縦中央揃えはどうすればいいですかね。
 
■padding
簡単なのはpaddingを利用する方法です。上下の長さが分かればそれに合わせてpaddingを指定すればOKです。

<style>
.component2-ex {
 line-height: 1; /* Initialize */
}
.component2-ex:after{ clear: both; display: block; content: ” }
.component2-ex .label {
 float: left;
 width: 300px;
 font-size: 16px;
 padding: 17px 0;
 text-align: center;
 background-color: #ccc;
}
.component2-ex .plus-btn {
 float: left;
 width: 50px;
 font-size: 24px;
 padding: 13px 0;
 text-align: center;
 background-color: #2c77f6;
 color: white;
}
</style>
<div class=”component2-ex”>
 <div class=”label”>Test Component</div>
 <div class=”plus-btn”>+</div>
</div>

出力結果

Test Component
+

 
■line-height
 
line-heightは本来行の間隔を表しますが、インライン要素の縦中央揃えにもよく使われます。この値は160%, 1.8などで使えるが、px単位でも使えます。
ただし、本来は行の間隔を表す属性のため、複数行のテキストには使えません。

<style>
.component3-ex:after{ clear: both; display: block; content: ” }
.component3-ex .label {
 float: left;
 width: 300px;
 height: 50px;
 font-size: 16px;
 line-height: 50px;
 text-align: center;
 background-color: #ccc;
}
.component3-ex .plus-btn {
 float: left;
 width: 50px;
 height: 50px;
 font-size: 24px;
 line-height: 50px;
 text-align: center;
 background-color: #2c77f6;
 color: white;
}
</style>
<div class=”component3-ex”>
 <div class=”label”>Test Component</div>
 <div class=”plus-btn”>+</div>
</div>

出力結果

Test Component
+

 
 
 
 

当サイトは広告を含めています。広告のクリックによる収益は全て当サイトの管理、維持、コンテンツ製作に使われます。

 

Team ladybird
タイトルとURLをコピーしました