LoginSignup
0
0

More than 3 years have passed since last update.

liタグの中のaタグを親要素いっぱいにし、かつテキストを上下左右中央にする方法。

Posted at

liタグの中のaタグを親要素いっぱいにし、かつテキストを上下左右中央にする方法について説明します。

【お願い】
自分も同じ内容で困っていたため、たくさん調べてようやくこの方法にたどり着き、解決することはできました。しかし、理論?はいまいち分かっていません。理論や仕組みが分かる方教えてください。また、問題点等もあれば教えていただきたいです。

【手順】
① liタグの中のaタグを親要素いっぱいにする。
② liタグの中のaタグのテキストを上下左右中央にする。

4つのボタンが横に並んでいるメニューのようなデザインにしました。
名前はシンプルにTest1...Test4です。

test.html

    <ul>
      <li>
        <a href="#">Test1</a>
      </li>
      <li>
        <a href="#">Test2</a>
      </li>
      <li>
        <a href="#">Test3</a>
      </li>
      <li>
        <a href="#">Test4</a>
      </li>
    </ul>
test.css
ul {
  display: flex;
}

li {
  list-style: none;
  width: 200px;
  height: 100px;
  background-color: #ffdab9;
  border: 1px solid #515151;
}

a {
  text-decoration: none;
  background-color: #ffc0cb;
  color: #515151;
}

liタグとaタグの違いをわかりやすくするために色を変えました。
liタグがオレンジでaタグがピンクです。

上記のコードだとこの状態です。↓

スクリーンショット 2020-07-05 19.19.48.png

【① liタグの中のaタグを親要素いっぱいにする。】

liタグの中に
display: table;
aタグの中にdisplay: table-cell;を書きます。

スクリーンショット 2020-07-05 19.23.20.png

aタグ(ピンク)が親要素いっぱいになりました。

【② liタグの中のaタグのテキストを上下左右中央にする。】

liタグにvertical-align: middle;
aタグにtext-align: center;を書く。

スクリーンショット 2020-07-05 19.32.53.png

完成です。

test.css
ul {
  display: flex;
}

li {
 list-style: none;
  width: 200px;
  height: 100px;
  background-color: #ffdab9;
  border: 1px solid #515151;
  display: table;
  text-align: center;
}

a {
 text-decoration: none;
  background-color: #ffc0cb;
  display: table-cell;
  vertical-align: middle;
 color: #515151;
}

display: table;はレスポンシブデザインで自由がきかないと出てきたので試してみました。
スクリーンショット 2020-07-05 19.54.20.png

どなたかこの方法をつかってレスポンシブデザインに対応させる方法か、liタグをa要素いっぱいにしてテキストを上下中央にし、レスポンシブデザインに対応させる方法を教えてください🙇🏻‍♀️

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