SHU BLOG

BLOG NEWS ブログ

TITLE

【CSS】初心者向け擬似要素、擬似クラスについて理解しましょう!

SHU[シュウ]

1991年生まれ九州の宮崎県育ち
高校卒業後、愛知県で自動車関係の
お仕事に5年間勤め、WEB業界に
転職致しました。
趣味:サッカー観戦、ゲーム、映画、漫画
基本インドアです!笑

シュウ
シュウ
今回は、【CSS】初心者向け擬似クラスにつてい解説していきます。

よく現場で使用している擬似クラスについて紹介するね!
ナカ君
ナカ君

擬似クラスについて

擬似クラスについて

擬似クラスって調べてみると結構あるのよね

そうなんだよね。
今回は現場でよく使用されている擬似クラスについて紹介していくよ!

簡単なサンプルのご用意

シンプルなリストを作成しましょう。
今回はリストタグを使い、項目を6つ用意しそれに対して擬似クラスを使用します。

<ul>
	<li>項目1</li>
	<li>項目2</li>
	<li>項目3</li>
	<li>項目4</li>
	<li>項目5</li>
    <li>項目6</li>
</ul>

See the Pen
GRJNpby
by shu (@shu0325)
on CodePen.

最初の要素にだけスタイルを適用する方法

:first-child擬似クラスは、
最初の子要素にスタイルが適用されます。

ul li:first-child{
	background-color: #e2d0b6;
}

See the Pen
KKpNdLE
by shu (@shu0325)
on CodePen.

最後の要素にだけスタイルを適用する方法

:last-child擬似クラスは、
最後の子要素にスタイルが適用されます。

ul li:last-child{
	background-color: #e2d0b6;
}

See the Pen
YzXpymx
by shu (@shu0325)
on CodePen.

偶数番目の要素にスタイルを適用する方法

:nth-child(even)擬似クラスは、
偶数の子要素にスタイルが適用されます。

ul li:nth-child(even){
	background-color: #e2d0b6;
}

See the Pen
abOBdoN
by shu (@shu0325)
on CodePen.

奇数番目の要素にスタイルを適用する方法

:nth-child(odd)擬似クラスは、
奇数の子要素にスタイルが適用されます。

ul li:nth-child(odd){
	background-color: #e2d0b6;
}

See the Pen
bGdBEbm
by shu (@shu0325)
on CodePen.

上からn番目の要素にスタイルを適用する方法

:nth-child(3)擬似クラスは、
上から3番目の子要素にスタイルが適用されます。
:nth-child(5)擬似クラスは、
上から5番目の子要素にスタイルが適用されます。

/*上から3番目の子要素を茶色*/
ul li:nth-child(3){
	background-color: #e2d0b6;
}
/*上から5番目の子要素を緑色*/
ul li:nth-child(5){
	background-color: #b3d3ae;
}

See the Pen
dyoOGyW
by shu (@shu0325)
on CodePen.

下からn番目の要素にスタイルを適用する方法

:nth-last-child(2)擬似クラスは、
下から2番目の子要素にスタイルが適用されます。
:nth-last-child(4)擬似クラスは、
下から4番目の子要素にスタイルが適用されます。

/*下から2番目の子要素を茶色*/
ul li:nth-last-child(2){
	background-color: #e2d0b6;
}
/*下から4番目の子要素を緑色*/
ul li:nth-last-child(4){
	background-color: #b3d3ae;
}

See the Pen
ExjNPaK
by shu (@shu0325)
on CodePen.

3の倍数の要素にスタイルを適用する方法

:nth-child(3n)擬似クラスは、
3の倍数の子要素にスタイルが適用されます。

ul li:nth-child(3n){
	background-color: #e2d0b6;
}

See the Pen
LYVbGpW
by shu (@shu0325)
on CodePen.

最初の文字にスタイルを適用する方法

::first-letter擬似クラスは、
最初の文字にスタイルが適用されます。

p::first-letter {
 color: #b3d3ae;
 font-size: 30px;
}

See the Pen
oNXYbLw
by shu (@shu0325)
on CodePen.

最初の行にスタイルを適用する方法

::first-line擬似クラスは、
最初の行にスタイルが適用されます。

p::first-line {
 color: #b3d3ae;
}

See the Pen
GRJNodw
by shu (@shu0325)
on CodePen.

beforeを適用する方法

::beforeを使用すると
要素の直前に要素が挿入されます。

ul li::before{
  content: '●';
  color:#b3d3ae;
}

See the Pen
XWbNdqY
by shu (@shu0325)
on CodePen.

afterを適用する方法

::afterを使用すると
要素の直後に要素が挿入されます。

ul li::after{
  content: '▲';
  color:#b3d3ae;
}

See the Pen
OJVbNrX
by shu (@shu0325)
on CodePen.

まとめ

今回はこれで以上です。

私がよく現場で使用する擬似要素、擬似クラスをまとめてみました。
擬似要素、擬似クラスは作業では確実に使用するので必ず覚えておきましょう!

スポンサーリンク

SHU

1991年生まれ九州の宮崎県育ち高校卒業後、愛知県で自動車関係のお仕事に5年間勤め、WEB業界に転職致しました。
趣味:サッカー観戦、ゲーム、映画、漫画基本インドアです!笑
つくる、しあわせをテーマとして主にWEBに関する様々な情報を発信しています。

最新記事

関連記事

オススメ記事

月別アーカイブ

page_top