常见的CSS选择器分类及具体代码示例
CSS选择器是用来选择HTML文档的元素并给予其特定样式的工具。掌握不同类型的CSS选择器对于编写高效的CSS样式表至关重要。下面是常见的CSS选择器分类以及具体的代码示例。
p {
color: blue;
}
.button {
background-color: red;
}
在HTML中的使用方式:
立即学习“前端免费学习笔记(深入)”;
<button class="button">Click me</button>
#header {
background-color: yellow;
}
在HTML中的使用方式:
立即学习“前端免费学习笔记(深入)”;
<header id="header">This is the header</header>
p > span {
color: red;
}
<p>This is a <span>red</span> text.</p>
p span {
background-color: gray;
}
<p>This is a <span>gray</span> text.</p>
h2 + p {
color: blue;
}
<h2>Heading 2</h2> <p>This paragraph is immediately following the h2 element.</p>
* {
border: 1px solid black;
}
以上是常见的CSS选择器分类及其示例代码。了解不同类型的选择器以及它们的用法,将有助于您在编写CSS样式表时更具灵活性和精确性。记住,选择器的组合和嵌套也可以与使用CSS选择器进行更具体的元素选择和样式定义。