LoginSignup
0
0

More than 1 year has passed since last update.

CSS実践(6) 「結合子を使ったセレクターの指定」

Last updated at Posted at 2021-08-25

1. はじめに

本記事では、CSSの
「結合子を使ったセレクターの指定」
について記載する。

2. 結合子を使ったセレクターの種類

<凡例>
結合子.png

3. ユニバーサルセレクター

ユニバーサルセレクターとは?

全ての要素を対象とする場合に使用する。

【サンプル】

index.html
<body>
  <h1>結合子を使ったセレクター</h1>
  <h2>今日の<strong>注意事項</strong></h2>
  <p>家に帰ったら<strong>手洗い</strong>をしましょう。</p>
  <p>アルコール消毒をしましょう。</p>
</body>
styles.css
* {
  margin: 0;
}

【表示例】
<before>
univ_bef.png

<after>
univ_aft.png

4. 子孫セレクター

子孫セレクターとは?

・親とその子孫という形で指定するセレクター。 ・親と子孫は半角スペースで区切る。 ・子孫はいくつでも指定できる。 ・idセレクターclassセレクター要素セレクターなど他のセレクターと組み合わせて指定します。

【サンプル】

index.html
<body>
  <h1>結合子を使ったセレクター</h1>
  <h2>今日の<strong>注意事項</strong></h2>
  <p>家に帰ったら<strong>手洗い</strong>をしましょう。</p>
  <p>アルコール消毒をしましょう。</p>
</body>
styles.css
p strong {
  color: red;
}

【表示例】
<before>
univ_bef.png
<after>
sison_aft.png

5. 子セレクター

子セレクターとは?

・親と直下の要素で指定するセレクターのこと。 ・親と子は「>」で区切る。 ・子は、いくつでも指定ができる。 ・子孫セレクタと同じくidセレクタclassセレクタ要素セレクタなど他のセレクタと組み合わせて指定する。 ・子孫セレクタとの違いは、親の直下の要素のみが対象となる。

【サンプル】

index.html
<body>
  <h1>結合子を使ったセレクター</h1>
  <h2>今日の<strong>注意事項</strong></h2>
  <p>家に帰ったら<strong>手洗い</strong>をしましょう。</p>
  <p>アルコール消毒をしましょう。</p>
</body>
styles.css
p > strong {
  color: red;
}

【表示例】
<before>
univ_bef.png
<after>
ko_aft.png

6. 隣接セレクター

セレクタを + で区切ると、同じ階層にある要素同士で、 ある要素の直後に隣接している要素を対象にスタイルを適用することができる。

【サンプル】

index.html
<body>
  <h1>結合子を使ったセレクター</h1>
  <h2>今日の<strong>注意事項</strong></h2>
  <p>家に帰ったら<strong>手洗い</strong>をしましょう。</p>
  <p>アルコール消毒をしましょう。</p>
</body>
styles.css
h2 + p {
  color: red;
}

【表示例】
<before>
univ_bef.png
<after>
rinsetu_aft.png

7. 間接セレクター

間接セレクターとは?

・親要素が同じ兄弟関係の弟に適用されるセレクター。 ・隣接セレクターは直後の弟に対してのみに対し、兄弟関係であれば間に別の要素が入っても適用される。

【サンプル】

index.html
<body>
  <h1>結合子を使ったセレクター</h1>
  <h2>今日の<strong>注意事項</strong></h2>
  <p>家に帰ったら<strong>手洗い</strong>をしましょう。</p>
  <p>アルコール消毒をしましょう。</p>
</body>
styles.css
h1 ~ p {
  color: red;
}

【表示例】
<before>
univ_bef.png
<after>
kansetu_aft.png

8. おわりに

次項:CSS実践(7) 「リンクで使用する擬似クラス」「フォント・ウェブフォントの指定」に続く。

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