类型选择器
类型指 h1 ,p,a这类
h1{
color:red;
}
全局选择器以 *开头
类选择器
.highlight {
background-color: yellow;
}
<h1 class="highlight">Class selectors</h1>
指向特定元素类
span.highlight {
background-color: yellow;
}
<p>Veggies es bonus vobis, proinde vos postulo essum magis <span class="highlight">kohlrabi welsh onion</span> daikon amaranth tatsoi tomatillo
melon azuki bean garlic.</p>
属性选择器
根据属性来
li[class] {
font-size: 200%;
}
li[class="a"] {
background-color: yellow;
}
li[class~="a"] {
color: red;
}
<h1>Attribute presence and value selectors</h1>
<ul>
<li>Item 1</li>
<li class="a">Item 2</li>
<li class="a b">Item 3</li>
<li class="ab">Item 4</li>
</ul>
- 使用
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
的属性,于是匹配了所有项。
伪类:伪类就是开头为冒号的关键字
<article>
<p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo
melon azuki bean garlic.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard
greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
</article>
伪元素开头为双冒号::
article p::first-line {
font-size: 120%;
font-weight: bold;
}
<article>
<p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo
melon azuki bean garlic.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard
greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
</article>
伪类和伪元素结合
article p:first-child::first-line { font-size: 120%; font-weight: bold; }
前后
这些伪元素的更推荐的用法是插入一个图标,例如下面的示例加入的一个小箭头,作为一个视觉性的提示,而且我们并不希望屏幕阅读器读出它。
.box::before {
content: "This should show before the other content. ";
}
<p class="box">Content in the box in my HTML page.</p>
选择器
后带选择器
下面的示例中,我们只会匹配处于带有.box
类的元素里面的<p>
元素。
.box p {
color: red;
}
<div class="box"><p>Text in .box</p></div>
<p>Text not in .box</p>
子代关系选择器是个大于号(>
),只会在选择器选中直接子元素的时候匹配。继承关系上更远的后代则不会匹配。例如,只选中作为<ul>
的直接子元素的<li>
元素:
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>
兄弟元素
如果你想选中一个元素的兄弟元素,即使它们不直接相邻,你还是可以使用通用兄弟关系选择器(~
)。要选中所有的<p>
元素后任何地方的<img>
元素,我们会这样做:
h1 ~ p {
font-weight: bold;
background-color: #333;
color: #fff;
padding: .5em;
}
<article>
<h1>A heading</h1>
<p>I am a paragraph.</p>
<div>I am a div</div>
<p>I am another paragraph.</p>
</article>