CSS selectors

2017-03-04  本文已影响0人  nicole914

1.class 和 id 的使用场景

-可以为任意多个元素指定同一个类,但一个ID选择器只能使用一次。因此在要重复使用某样式时为元素指定类,而一个特殊的样式应该使用ID选择器。
-不同于类选择器,ID选择器不能结合使用,因为ID属性不允许有以空格分隔的词列表。
-ID选择器的优先级要比类选择器更高。

2.CSS常见选择器(以选择器类型划分)

Simple selectors

Attribute selectors

// 有attr属性的元素
[attr]
// attr属性值为val的元素
[attr = val]
// 包含值为val的attr属性的元素
[attr ~= val]
// attr属性值为val或以val开头的元素
[attr |= val]
// attr属性值以val开头的元素
[attr ^= val]
// attr属性值以val结尾的元素
[attr $= val]
// attr属性值包含子串val的元素
[attr *= val]

Pseudo

:link, :visited, :focus, :hover, :active
:first-child, :first-of-type, :last-child, :last-of-type, :nth-child(), :nth-of-type(), :nth-last-child(), :nth-last-of-type(), :only-child, :only-of-type
:not()
:checked, :disabled, :enabled, :required, :optional, :valid, :invalid
:target
::before, ::after
::first-letter, ::first-line
::selection

Combinators and Multiple selectors

// 同时匹配
AB
// 匹配A的后代B
A B
// 匹配A的直接后代B
A>B
// 匹配A后的相邻的兄弟元素B
A+B
// 匹配A后的所有的兄弟元素B
A~B

3.择器的优先级

层叠规则:

4.a:link, a:hover, a:active, a:visited 的顺序

a:link > a:visited > a:fovus > a.hover > a.active
以上选择器的优先级别相同,后面的样式会覆盖前面的样式。
正在“点击”的“未访问”链接可同时与:link, :hover, :active匹配,所以:active要放到最后。其他同理。

5.

/*ID为header的元素*/
#header{
}
/*类名为header的元素*/
.header{
}
/*类名为logo,且祖先类名为header的所有元素*/
.header .logo{
}
/*类名同时有header和mobile的元素*/
.header.mobile{
}
/*祖先类名为header的p元素和h3元素 */
.header p, .header h3{
}
/*所有li元素,且父类名为nav,且祖先ID为header*/
#header .nav>li{
}
/*所有悬停的a元素,且祖先ID为header*/
#header a:hover{
}
/*所有类名为logo的元素后的兄弟元素p元素,且祖先ID为header*/
#header .logo~p{
}
/*所有type属性为text的input元素,且祖先ID为header*/
#header input[type="text"]{
}
<style>
/*将div下第一个类名为item1的元素字体设为红色*/
.item1:first-child{
  color: red;
}
/*将div下同一类标签的第一个元素背景设为blue*/
.item1:first-of-type{
  background: blue;
}
</style>
 <div class="ct">
   <p class="item1">aa</p>
   <h3 class="item1">bb</h3>
   <h3 class="item1">ccc</h3>
 </div>
上一篇 下一篇

猜你喜欢

热点阅读