大阪府堺市のWEB制作(ホームページ制作)事務所です

[CSS]擬似クラス擬似要素:まとめ

最終更新日:2022.05.23 [月] 公開日:2017.11.19 [日] カテゴリー:html・CSS・jQuery・JS備忘

擬似クラスとてもよく使うので、備忘的にまとめます。




基本のhtmlベース

html

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • ここにまとめが入ります

【:first-child :last-child】要素内の最初の子要素と最後の子要素の指定

CSS

.test1 ul :first-child{
color:#00ff00;
}
.test1 ul :last-child{
color:#ff0000;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1

ここにまとめが入ります

【:nth-child(n)】親要素の中のn番目の子要素の指定

CSS

.test2 ul :nth-child(3){
color:#ff0000;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1

ここにまとめが入ります

【:nth-child(enev)】【:nth-child(odd)】親要素の中の偶数(even)奇数(odd)

CSS

.test3 ul :nth-child(even){
color:#0000ff;
}
.test3 ul :nth-child(odd){
color:#00ff00;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1

ここにまとめが入ります

【:nth-of-type(n)】指定した子要素の種類限定のn番目

CSS

/*test4の中のpタグの2番目を指定:赤色
今回の例だとpタグの2番目はラストのまとめの文章*/
.test4 p:nth-of-type(2){
color:#ff0000;
}
/*test4の中のliタグの2番目を指定:水色*/
.test4 li:nth-of-type(2){
color:#00ffff;
}
/*test4の中のliタグの最初を指定:黄色*/
.test4 li:first-of-type{
color:#ffcc00;
}
/*test4の中のliタグの最後を指定:ピンク*/
.test4 ul li:last-of-type{
color:#ff00ff;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1

ここにまとめが入ります

【:empty】空の要素を指定

CSS

.test5 li:empty{
background-color:#000;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • ↑テストのため空要素入れました。

  • リスト1
  • リスト1

ここにまとめが入ります

【:not】否定擬似クラス

CSS

/*ulの中の最後の要素以外を背景ピンクに*/
.test6 ul :not(:last-child){
background-color:#fae5fa;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1

ここにまとめが入ります

【::before】【::after】要素の前後にスタイルを当てる

CSS

.test7 p::before{
content:'■';
color:#f00;
}
.test7 li::after{
content:'新着';
color:#f00;
margin-left:20px;
font-size:10px;
}

表示

ここに説明文が入ります

  • リスト1
  • リスト1
  • リスト1
  • リスト1
  • リスト1

ここにまとめが入ります


スポンサーリンク

コメントを残す