Klassenselektoren
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Der CSS Klassenselektor stimmt mit Elementen basierend auf dem Inhalt ihres class
-Attributs überein.
/* All elements with class="spacious" */
.spacious {
margin: 2em;
}
/* All elements with class="spacious" */
li.spacious {
margin: 2em;
}
/* All elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
margin: 2em;
}
Syntax
.class_name {
/* … */
}
Beachten Sie, dass dies dem folgenden Attributselektor entspricht:
[class~="class_name"] {
/* … */
}
Der class_name
-Wert muss ein gültiger CSS-Bezeichner sein. HTML-class
-Attribute, die keine gültigen CSS-Bezeichner sind, müssen escaped werden, bevor sie in Klassenselektoren verwendet werden können.
Beispiele
Gültige Klassenselektoren
HTML
This paragraph has red text.
This paragraph has red text and a yellow background.
This paragraph has red text and "fancy" styling.
This is just a regular paragraph.
This paragraph has a pink background.
This paragraph has a yellow background.
CSS
.red {
color: #f33;
}
.yellow-bg {
background: #ffa;
}
.fancy {
font-weight: bold;
text-shadow: 4px 4px 3px #77f;
}
/* In the next two rules, the class attributes must be escaped */
.item\?one {
background-color: pink;
}
.\00003123item {
background-color: yellow;
}
Ergebnis
Ungültige Klassenselektoren
Die Klassenselektoren in den folgenden Regeln sind keine gültigen CSS-Bezeichner und werden ignoriert.
.item?one {
background-color: green;
}
.123item {
background-color: green;
}
Spezifikationen
Specification |
---|
Selectors Level 4 # class-html |