LoginSignup
1
0

More than 1 year has passed since last update.

CSSの擬似クラスと擬似要素

Last updated at Posted at 2022-12-10

ひとりCSS Advent Calendar 2022 11日目です。

擬似クラスと疑似要素のことです。

よく使いそうな擬似クラス

便利そう

  • :not() - 当てはまらないとき。よく使う
  • :has() - ()の中のものを持つ
  • :is() - ()の中のいずれかに当てはまる。引数内で最も詳細度の高いセレクターの詳細度
  • :where() - ()の中のいずれかに当てはまる。詳細度は0
  • :lang() - ()の中の言語に当てはまる。
  • :target - URLのフラグメントに一致するidを持つ要素

リンクやボタン

  • :hover - カーソルがあたっているとき
  • :active - クリックした直後
  • :focus - フォーカスしたとき
  • :focus-visible - ユーザーエージェントの動作によってフォーカスしたりしなかったりする
    • (主にキーボードでのフォーカスに反応するがマウスでは反応しないっぽい)
  • :focus-within - 子孫要素にフォーカスがある場合

入力系

  • :autofill
  • :enabled
  • :disabled
  • :read-only
  • :read-write
  • :placeholder-shown
  • :default
  • :checked
  • :indeterminate
  • :blank
  • :valid
  • :invalid
  • :in-range
  • :out-of-range
  • :required
  • :optional
  • :user-invalid

ツリー構造

  • :root
    • 文書のルート(基本はHTML)
  • :empty
    • ホワイトスペース以外に子がない要素
  • :first-child / :last-child / :only-child
    • 兄弟のうちの最初の要素、最後の要素、要素内に兄弟がない場合
  • :nth-child / :nth-last-child
    • 個数
  • :first-of-type / :last-of-type / :only-of-type
    • 兄弟のうち、最初の特定の型、最後の特定の型、兄弟要素がない要素
  • :nth-of-type / :nth-last-of-type
    • 個数

ほかは以下
https://developer.mozilla.org/ja/docs/Web/CSS/Pseudo-classes

よく使いそうな疑似要素

  • ::before (:before) - コンテンツのまえ
  • ::after (:after) - コンテンツのあと
  • ::first-letter (:first-letter) - ひともじめ
  • ::first-line (:first-line) - いちぎょうめ
  • ::marker - リストの装飾
  • ::placeholder - inputやtextarea内が空のときのテキストのスタイル
  • ::selection - 選択時のスタイル

ほかは以下
https://developer.mozilla.org/ja/docs/Web/CSS/Pseudo-elements

::beforeと::after

  • インライン
  • 二重コロンはCSS3での書き方。
    • :hover のような擬似クラスと区別するために導入された。
    • :before、:after のようにコロン一つでもOK(これはCSS2での書き方)
  • よくある使い方
    • content プロパティを使用して、要素に装飾的な内容を追加する
  • select 要素には疑似要素を作れない

サンプル

<p>Paragraph</p>
p::before, p::after {
  font-weight: bold;
  font-size: 50%;
  padding: 1em;
}
p::before {
  content: 'before';
}

p::after {
  content: 'after';
}

image.png

参考

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