CSS 选择器(基本选择器)
基本选择器
选择器 | 示例 | 描述 |
.class | .intro | 选择 class="intro" 的所有元素 |
#id | #firstname | 选择 id="firstname" 的所有元素 |
* | * | 选择所有元素 |
element | p | 选择所有元素 |
element,element | div,p | 选择所有元素和所有元素 |
element element | div p | 选择元素内部的所有元素 |
element>element | div>p | 选择父元素为元素的所有元素 |
element+element | div+p | 选择紧接在元素之后的所有元素 |
标签选择
使用 * 可为所有元素设置样式。
* {
text-decoration: none;
color: #6c757d;
}
根据标签为元素设置样式
h1 {
color: red;
}
同时设置多个元素组合
h1,h2 {
color: red;
}
元素在多个组件中存在
h1,h2 {
color: red;
}
h1,h3{
background: #dcdcdc;
}
类选择器
类选择器是为一类状态声明样式规则,下面是把文本居中定义为类样式。
<style>
.text-center {
text-align: center;
}
</style>
<h1 class="text-center">https://blog.csdn.net/weixin_44541438</h1>
<h2 class="text-center">贼贼</h2>
将类选择器指定为具体标签
<h1 class="text-center">https://blog.csdn.net/weixin_44541438</h1>
<h2 class="text-center">贼贼</h2>
.help-block {
background: red;
}
span.help-block {
font-size: 12px;
color: #aaa;
background: none;
}
...
<span class="help-block">类选择器</span>
#ID选择器
为有 id 属性的元素设置样式
#container {
background: red;
}
...
<h1 id="container">https://blog.csdn.net/weixin_44541438</h1>
文档中ID应该是唯一的,虽然为多个元素设置同一个ID也可以产生样式效果,但这是不符合规范的。
建议优先使用类选择器