CSS 类选择器 Class selectors
类选择器 Class selector:按照给定的 class 属性的值,选择所有匹配的元素。使用 .类名 .classname。比如 .index 会匹配任何 class 属性中含有 "index" 类的元素。
类选择器 Class selector
/* All elements with class="spacious" */
.spacious {
margin: 2em;
}
/* All <li> elements with class="spacious" */
li.spacious {
margin: 2em;
}
/* All <li> elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
margin: 2em;
}
在一个 HTML 文档中,CSS 类选择器会根据元素的类属性中的内容匹配元素。类属性被定义为一个以空格分隔的列表项,在这组类名中,必须有一项与类选择器中的类名完全匹配,此条样式声明才会生效。
- 语法:
.classname - 例子:
.index匹配任何 class 属性中含有 "index" 类的元素。
注意它与下面的语句等价 attribute selector: [class~=类名] { 样式声明 }
- HTML
- CSS
<p class="darkviolet">This paragraph has darkviolet text.</p>
<p class="dodgerblue-bg"> This paragraph has dodgerblue background.</p>
<p class="indianred fancy">This paragraph has indianred text and "fancy" styling.</p>
<p>This is just a regular paragraph.</p>
.darkviolet {
color: darkviolet;
}
.indianred {
color: indianred;
}
.dodgerblue-bg {
background: dodgerblue;
}
.fancy {
font-weight: bold;
text-shadow: 4px 4px 3px #77f;
}
http://localhost:3000/css-class-selectors.html
This paragraph has darkviolet text.
This paragraph has dodgerblue background.
This paragraph has indianred text and "fancy" styling.
This is just a regular paragraph.