LoginSignup
3
3

More than 1 year has passed since last update.

【CSS】よく使うセレクターをまとめてみた

Posted at

はじめに

開発現場でよく使うCSSのセレクターをまとめてみました。随時追加していく予定です。

タイプセレクター

html
 <div>こちらはdivタグです。</div>
css
div {
  color: red;
}
  • カンマ区切りでも使える
css
div, p {
  color: red;
}

classによるセレクター

html
 <p class="ptag">こちらpタグです。</p>
css
.ptag{
  background-color: gold;
}

idによるセレクター

html
 <p id="ptag">こちらpタグです。</p>
css
#ptag{
  background-color: gold;
}

ユニバーサルセレクター

css
* {
  color: blue;
}

属性によるセレクター

指定した属性によるセレクター

html
<a href="https://www.kddi.com/">KDDI</a>
css
a[href]{
  color: green;
}

部分文字列一致セレクター

全文一致

html
<a href="https://www.kddi.com/">KDDI</a>
css
a[href="https://www.kddi.com/"]{
  color: green;
}

前文部分一致

  • 前文部分一致させる場合は、^を使う
html
<a href="https://www.kddi.com/">KDDI</a>
css
a[href^="https://www."]{
  color: green;
}

後文部分一致

  • 後文部分一致させる場合は、$を使う
html
<a href="https://www.kddi.com/">KDDI</a>
css
a[href$="com/"]{
  color: green;
}

指定の文字を含む場合のみ

  • 指定の文字の場合は、*を使う
html
<a href="https://www.kddi.com/">KDDI</a>
css
a[href*="kddi"]{
  color: green;
}

擬似クラス及び疑似要素によるセレクター

最初の要素を選択するfirst-of-type

html
    <article>
      <h1>h1タグです</h1>
      <p>1番目</p>
      <p>2番目</p>
      <p>3番目</p>
    </article>
css
article p:first-of-type{
  color: red;
}

最後の要素を選択する last-of-type

html
    <article>
      <h1>h1タグです</h1>
      <p>1番目</p>
      <p>2番目</p>
      <p>3番目</p>
    </article>
css
article p:last-of-type{
  color: red;
}

好きな順番の要素を選択するnth-of-type()

html
    <article>
      <h1>h1タグです</h1>
      <p>1番目</p>
      <p>2番目</p>
      <p>3番目</p>
    </article>
  • 2番目を選択する場合
css
article p:nth-of-type(2){ 
  color: red;
}

最初以外を選択する場合:not(:first-of-type)

html
    <article>
      <h1>h1タグです</h1>
      <p>1番目</p>
      <p>2番目</p>
      <p>3番目</p>
    </article>
css
article p:not(:first-of-type){
  color: red;
}

選択したときの色を変更させるhover

html
    <article>
      <h1>h1タグです</h1>
      <p>1番目</p>
      <p>2番目</p>
      <p>3番目</p>
    </article>
css
p:hover{
  background-color: pink;
}
3
3
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
3
3