HTMLセレクタの種類と使用方法

基本セレクタ

HTML要素を選択するための基本的なセレクタには以下のものがあります。

IDセレクタ

IDセレクタはページ内で一意である必要があり、#記号を使用します。

#header {
    background-color: blue;
}

クラスセレクタ

クラスセレクタは複数の要素に適用可能で、.記号を使用します。一つの要素に複数のクラスを指定することも可能です。

.highlight {
    color: red;
}

.note.warning {
    border: 1px solid orange;
}

全称セレクタ

すべての要素にスタイルを適用する場合に使用します。

* {
    margin: 0;
    padding: 0;
}

複合セレクタ

交差セレクタ

複数の条件を同時に満たす要素を選択します。要素セレクタが含まれる場合は先頭に配置する必要があります。

div.container.active {
    display: block;
}

グループ化セレクタ

複数のセレクタに対して同じスタイルを適用したい場合に使用します。

h1, h2, h3 {
    font-family: Arial, sans-serif;
}

階層セレクタ

要素間の親子関係や兄弟関係に基づいて要素を選択します。

直接子セレクタ

指定された親要素の直接の子要素のみを選択します。

nav > ul {
    list-style: none;
}

子孫セレクタ

指定された要素内のすべての子孫要素を選択します。

article p {
    line-height: 1.6;
}

隣接兄弟セレクタ

同じ親要素を持つ隣接する兄弟要素を選択します。

h2 + p {
    margin-top: 0;
}

一般兄弟セレクタ

同じ親要素を持つ後続のすべての兄弟要素を選択します。

li ~ li {
    margin-left: 10px;
}

属性セレクタ

要素の属性に基づいて選択を行います。

[target] {
    color: blue;
}

input[type="submit"] {
    background-color: green;
}

img[src^="https"] {
    border: 2px solid green;
}

a[href$=".pdf"] {
    background-image: url(pdf-icon.png);
}

[class*="btn"] {
    cursor: pointer;
}

疑似クラスセレクタ

要素の特定の状態や位置に基づいて選択します。

構造疑似クラス

tr:first-child {
    font-weight: bold;
}

tr:last-child {
    border-bottom: 2px solid black;
}

li:nth-child(odd) {
    background-color: #f0f0f0;
}

li:nth-child(3n) {
    color: red;
}

タイプ別構造疑似クラス

p:first-of-type {
    text-indent: 2em;
}

img:last-of-type {
    float: right;
}

div:nth-of-type(2n+1) {
    clear: both;
}

否定疑似クラス

input:not([type="hidden"]) {
    border: 1px solid #ccc;
}

p:not(.special) {
    color: #333;
}

リンク関連疑似クラス

a:link {
    color: blue;
}

a:visited {
    color: purple;
}

a:hover {
    text-decoration: underline;
}

a:active {
    color: red;
}

疑似要素セレクタ

実際には存在しない要素や特別な位置を表すために使用します。

p::first-letter {
    font-size: 2em;
    float: left;
}

blockquote::first-line {
    font-weight: bold;
}

p::selection {
    background-color: yellow;
}

.tooltip::before {
    content: "[注意]";
    color: red;
}

.quote::after {
    content: """;
    font-size: 1.2em;
}

スタイルの継承

親要素に設定した一部のスタイルは、子要素に自動的に継承されます。

body {
    font-family: "Meiryo", sans-serif;
    color: #333;
    /* 背景色やマージンなどのプロパティは継承されない */
}

継承される主なプロパティにはテキスト関連のプロパティ(color, font-family, font-sizeなど)がありますが、ボックスモデル関連のプロパティ(margin, padding, borderなど)や背景関連のプロパティは継承されません。

タグ: HTML CSS セレクタ 疑似クラス 疑似要素

6月28日 17:32 投稿