美文网首页
CSS selectors

CSS selectors

作者: nicole914 | 来源:发表于2017-03-04 12:14 被阅读0次

1.class 和 id 的使用场景

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

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

Simple selectors

  • 元素选择器
  • 类选择器(.
  • ID选择器(#
  • 通配选择器(*

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.择器的优先级

层叠规则:

  • !important标志的规则。
  • 内联样式。
  • 0,0,0,1:
    元素(h1)和伪元素(::before
  • 0,0,1,0:
    类选择器,属性选择器([type=“radio”])和伪类(:hover
  • 0,1,0,0:
    ID选择器
    Note:
    通配选择器*,结合符(+,>,~,),否定伪类(:not())对优先级没有影响。

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"]{
}
  • 伪类选择器见题2
  • div:first-child和div:first-of-type的作用和区别
    div:first-child:作为某元素第一个子元素的所有div元素
    div:first-of-type:作为某元素子元素的所有第一个div元素
<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>

相关文章

网友评论

      本文标题:CSS selectors

      本文链接:https://www.haomeiwen.com/subject/tvodgttx.html