LoginSignup
1
0

More than 1 year has passed since last update.

便利なクラス指定方法

Posted at

こんな要素があります

divに囲まれたpタグ達


<div>
  <p>要素1</p>
  <p>要素2</p>
  <p>要素3</p>
  <p>要素4</p>
  <p>要素5</p>
</div>

nth系の擬似クラスを使う

特定要素配下の最初か最後の要素を指定して、スタイルを付けることができます。

/* div直下の最初 */
div > p:first-child {
  background: yellow;
}
/* div直下の最後 */
div > p:last-child {
  background: tomato;
}

8f5e64b094a4982135804a5457412d8c.png

偶数要素と奇数要素のみにスタイルを付与するには、

/* 偶数(even) */
p:nth-child(even) {
  background-color: skyblue;
}
/* 奇数(odd) */
p:nth-child(odd) { 
  background-color: skyblue;
}

奇数の方を適用させたらこんな感じになります。

d385eb01b2ba4b3d4a329fc6110a53de.png

基本的な :nth-child(3) のように順番を使用するパターンに加え、
下記のように、3番目から7番目、みたいなこともできます。
p:nth-child(n+3):nth-child(-n+7)

[ ] かくかっこ を使う

[ ] は属性をあらわすセレクタで、^ を $ にすると「指定した文字列で終わる」、 * にすると「指定した文字列が含まれている。という意味になります。

body > [class*="btn"] {
    display: none;
}

クラスに btn という文字列を含む要素全て。

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