2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

background-colorをbackgroundで一括指定にしてはいけない理由

Posted at

background-colorの省略記法に知見がありましたので共有します。

海外の動画ですが、こちらを引用させていただいております。

background-colorは以下のように一括指定記法を用いてbackgroundで省略することができます。

style.css
div {
	background: #fff;
}

しかし、このような場合はどうでしょうか。

index.html
<div class="hero inverted">This is hero area</div>
style.css
.hero {
	background-image: url(./images/hero.jpg);
	background-size: cover;
	height: 500px;
	font-size: 5rem;
	text-align: center;
	line-height: 500px;
}

.inverted {
	color: #fff;
	background: #333;
}

同一のdiv内に複数のクラスを設定しており、.invertedで一括指定記法を使って背景に#333を指定しています。

これはこのように表示されます。

2022-03-26_18h15_40.png

.heroで指定しているはずの背景画像が表示されません。

原因を開発ツールで確認してみましょう。

2022-03-26_18h16_59.png

background-imageinitialで上書きされ、.heroで指定した背景画像が無効化されています。

これはなぜかというと、.invertedで一括指定記法で記述したbackground-color以外は指定なしと見做され、initialが指定されているというわけです。initialは初期値という意味です。

参考にbackgroundで関連のプロパティー一覧です。

プロパティ 初期値 意味
background-image none 背景画像を設定する
background-position 0% 0% 背景画像の初期位置を設定する
background-size auto auto 要素の背景画像の寸法を設定する
background-repeat repeat 背景画像をどのように繰り返すかを設定する
background-attachment scroll 背景画像の固定・移動を指定する
background-origin padding-box 背景の基準位置を指定する
background-clip border-box 背景の適用範囲を指定する
background-color transparent 背景の色を指定する

画像を表示させるには、きちんとbackground-colorと省略せずに記述すればOKです。

style.css
.inverted {
	color: #fff;
	background-color: #333;
}

2022-03-26_18h29_24.png

意図したところにのみCSSが当たります。

2022-03-26_18h31_10.png

この例からもわかる通り、そもそもbackgroundbackground-に続く複数のプロパティを一括で指定するためのものであり、ただ省略したいがために使うべきではありません。

私は元々きちんとbackground-colorを使う派だったのですが、一時期調べ物をしているうちにbackgroundで省略している記事が非常に多いことから真似をして省略するようになってしまいました。今でもかなり見かけます。

意図して省略しているならいいですが、そうでなければ省略はすべきではないと私は思います。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?