【CSS】line-heightとは?line-height:1px;の使い方


CSSのline-heightとは何でしょう?
line-height:1px;とはどんな時に使うのでしょうか?
line-heightとは
line-heightとは行の高さを指定するプロパティです。
例えば下のようにフォントサイズ10pxのテキストに
「line-height:30px;」を指定した場合テキストの上下に10pxずつの余白ができます。
行(line-height)の中でテキストは上下中央に表示されます。

line-heightプロパティは子要素に継承されるため、bodyに指定しておけばページ全体を管理できるため便利です。
line-heightの単位
line-heightプロパティで指定できる単位は「normal(初期値)」、「%」、「px」などがあります。
line-heightはどのくらいで指定すればよいのか?
フォントサイズにもよりますが一般的に「line-height: 1.5;」~「line-height: 2;」くらいが適当とされています。

h1で「「line-height: 2;」に指定してみました。ちょうどよいですね。

pタグでもちょうど良さそうですね。
好みにもよりますが1.5から2くらいでちょうど良さそうです。
line-height:1px;とは
line-height:1px;と指定してあるものを見かけると思います。
このようによくあるヘッダー。
<h1>のロゴと<li>のナビゲーションを横並びにしました。
<header id="header" class="wrapper">
<h1 class="site-title"><img src="img/logo1.png" alt=""></h1>
<nav>
<ul>
<li>HOME</li>
<li>CONTACT</li>
</ul>
</nav>
</header>

ところがデベロッパーツールで見るとこのように「logo」マークの下には変な余白が入っています。
「align-items: center;」もあてて縦方向中央に指定しているにも関わらず、その余白のせいで「nav」より上に表示されてしまっています。
#header {
display: flex;
justify-content: space-between;
align-items: center;
margin: 0 auto;
}

line-height:1px;を指定する
そこで「line-height:1px;」と<h1>の高さよりも小さい値の「line-height」を指定することで<h1>の上下の余白が消えて<nav>の高さと揃えることができました。
.site-title {
width: 120px;
line-height:1px;
padding: 10px 0;
}

テキストを上下中央にする
先程「line-height」で指定するとテキストは中央に配置できるとお伝えしました。
ですから例えばこのようにボックスの中でテキストを中央にしたいという時

「line-height」ボックスの高さを指定すればちょうど真ん中にテキストが表示されます。
今回の場合は赤いボックスの高さが200pxなので

「line-height: 200px;」と指定するとテキストはボックスの上下中央に表示されます。
.red {
width: 200px;
height: 200px;
background-color: red;
color: #fff;
line-height: 200px;
}
同じカテゴリの記事一覧へ