css选择器|青训营

107 阅读2分钟

1.类型选择器(也称为标签选择器)

2.类选择器,id选择器(. #)

(1)一个类对应多个元素

span.highlight {
    background-color: yellow;
}
​
h1.highlight {
    background-color: pink;
}
类名相同,所在元素不同

(2)

复合选择器:【空格】连接一个或多个选择器

当一个元素的class属性包含"notebox"和"warning"两个类名时,也就是class=notebook warning,它会匹配.notebox.notebox.warning这两个选择器的规则

.notebox {
  border: 4px solid #666;
  padding: .5em;
}
​
.notebox.warning {
  border-color: orange;
  font-weight: bold;
}
<div class="notebox">
    This is an informational note.
</div>
​
<div class="notebox warning">
    This note shows a warning.
</div>

3.属性选择器

存否和值选择器

  • 使用li[class],我们就能匹配任何有 class 属性的选择器。这匹配了除了第一项以外的所有项。
  • li[class="a"]匹配带有一个a类的选择器,不过不会选中一部分值为a而另一部分是另一个用空格隔开的值的类,它选中了第二项。
  • li[class~="a"]会匹配一个a类,不过也可以匹配一列用空格分开、包含a类的值,它选中了第二和第三项。

子字符串匹配选择器

  • li[class^="a"]匹配了任何值开头为a的属性,于是匹配了前两项。
  • li[class$="a"]匹配了任何值结尾为a的属性,于是匹配了第一和第三项。
  • li[class*="a"]匹配了任何值的字符串中出现了a的属性,于是匹配了所有项。

大小写不敏感选择器

li[class^="a" i] {
    color: red;
}

4.伪类选择器

简单伪类

  • first-child 兄弟元素里的第一个
  • last-child 兄弟元素里的最后一个
  • only-child 没有兄弟元素的
p:last-child {
  color: lime;
  background-color: black;
  padding: 5px;
}
<div>
  <p>This text isn't selected.</p>
  <p>This text is selected!</p>
</div>

用户行为伪类

  • :hover只会在用户将指针挪到元素上的时候才会激活,一般就是链接元素。
  • :focus只会在用户使用键盘控制,选定元素的时候激活。

5.伪元素

  • ::first-line 永远根据页面显示选中第一行
  • ::before ::after(永远和content绑定使用,可以加文字/图块)
.box::after {
    content: " ➥";
}   
<p class="box">Content in the box in my HTML page.</p>

6.关系选择器

后代选择器

.box p {
    color: red;
} 

子代选择器

是一个> 选中框架内所有直接子代

ul > li {
    border-top: 5px solid red;
}  
<ul>
    <li>Unordered item</li>
    <li>Unordered item
        <ol>
            <li>Item 1</li>
            <li>Item 2</li>
        </ol>
    </li>
</ul>

临接兄弟选择器

是一个+ 选中同级元素的下一个

h2 + p {
  color: red;
}