- 任意の横幅と高さが存在する
- コンテンツ(テキスト)が中央に配置されている
目次
『text-align: center』と『上下padding』を利用する方法
CSS設計完全ガイド ~詳細解説+実践的モジュール集のボタンパーツ実装で紹介されている方法です。
width
で横幅を指定し、text-align: center
でテキストを左右中央よせにします。高さに関してはpadding
でサイズの指定と上下中央よせを行います。
ブロックレベル要素の場合の具体例
<div class="btn">ボタン</div>
.btn {
width: 200px;
max-width: 100%;
padding: 20px 10px; /* 上下の20pxで高さの確保とテキストの上下中央よせを行う。左右10pxはテキストが横幅いっぱいに埋まるのを防ぐため */
background-color: lightblue;
text-align: center;
}
See the Pen
button-padding-block by Toshiharu Nishina (@nishina555)
on CodePen.
インライン要素の場合の具体例
【CSS】ブロック/インライン/インラインブロックの違いについてで紹介したとおり、インライン要素は横幅・高さの指定ができません。
ですのでdisplay: inline-block
を適用し、width
や上下のpadding
を指定できるようにします。サイズを指定できればよいのでdisplayの値はflexやblockでも問題ありません。
<a class="btn" href="#">ボタン</a>
.btn {
display: inline-block; /* インライン要素の場合は横幅・高さを指定できるようにするため、displayプロパティを追加する */
width: 200px;
max-width: 100%;
padding: 20px 10px;
background-color: lightblue;
text-align: center;
text-decoration: none;
}
See the Pen
button-padding-inline by Toshiharu Nishina (@nishina555)
on CodePen.
Flexboxの『justify-content: center』と『align-items: center』を利用する方法
Flexboxはレイアウトのように大きなパーツを配置する際に便利な機能ですが、テキスト中央よせを実装する際にも活躍します。
display: flex
で要素をFlexbox化し、justify-content: center
とalign-items: center
を指定することでテキストが中央よせになります。
ブロックレベル要素の場合の具体例
<div class="btn">ボタン</div>
.btn {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
max-width: 100%;
height: 50px;
padding: 10px 10px;
background-color: lightblue;
text-align: center;
}
See the Pen
button-flexbox-block by Toshiharu Nishina (@nishina555)
on CodePen.
インライン要素の場合の具体例
Flexboxの概要と使いどころでも紹介した通り、Flexbox内ではインライン要素も横幅・高さの指定が可能です。
ですので、ブロックレベル要素の時と同じ方法で実装できます。
<a class="btn" href="#">ボタン</a>
.btn {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
max-width: 100%;
height: 50px;
padding: 10px 10px;
background-color: lightblue;
text-align: center;
text-decoration: none;
}
See the Pen
button-flexbox-inline by Toshiharu Nishina (@nishina555)
on CodePen.
buttonタグ内のテキストはデフォルトで左右中央よせになります。
ですので、たとえばpadding
を上下左右に用意するだけで任意の幅のボタンパーツを作成できます。
See the Pen
button-button-tag by Toshiharu Nishina (@nishina555)
on CodePen.
さいごに
Twitter(@nishina555)やってます。フォローしてもらえるとうれしいです!