13
13

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.

特定のCSSプロパティが ::after や ::before などの擬似要素に適用されない場合の解決策

Last updated at Posted at 2015-04-22

::after や ::before などの擬似要素に対してスタイルを指定する際、上位のセレクタで指定した特定のプロパティが期待通りに適用されない場合があります。

擬似要素にスタイルが適用されない例

下の例では、全称セレクタ(*)で "box-sizing" プロパティと "color" プロパティを指定していますが、#sample_02 の ::after擬似要素には "color: red" の指定のみが適用されていることがわかります。

HTML
<div id="sample_01"></div>
<div id="sample_02"></div>
CSS
* {
	box-sizing: border-box; /* 擬似要素には適用されない */
	color: red;
}

# sample_01 {
	width: 100px;
	height: 100px;
	padding: 10px;
	border: 20px solid blue;
}

# sample_02::after {
	content: 'after';
	display: block;
	width: 100px;
	height: 100px;
	padding: 10px;
	border: 20px solid blue;
}

sample_css_after.png

継承プロパティと非継承プロパティ

上位のセレクタで指定したプロパティが擬似要素に適用されるかどうかは、そのプロパティが【継承プロパティ】か【非継承プロパティ】かに依ります。

【非継承プロパティ】である "box-sizing" はそのままでは擬似要素に適用されないため、以下のようにCSSを調整する必要があります。

CSS
* {
	box-sizing: border-box;
	color: red;
}

*::before,
*::after {
	box-sizing: border-box; /* 擬似要素にも同様のプロパティを指定 */
}

プロパティ値を inherit とすることで明示的に「継承」させることも可能です。

CSS
* {
	box-sizing: border-box;
	color: red;
}

*::before,
*::after {
	box-sizing: inherit; /* 継承 */
}

全称セレクタ(*)は、一般的には「すべての要素にマッチし一括でスタイルを適用できる」と説明されますが、::after や ::before などの擬似要素と組み合わせて使用する際には注意が必要です。
(全称セレクタを使用することの是非については本記事では触れません。)

なお、CSSプロパティの「継承(inheritance)」の概念についてはMDNの記事が参考になります。
inheritance - CSS | MDN

13
13
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
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?