CSS选择器

2017-02-25  本文已影响0人  ychenxi

Class 和 id 的使用场景?

CSS选择器常见的有几种?

选择器 功能
* 通用元素选择器,匹配页面任何元素
#id id选择器,匹配特定的id的元素
.class 类选择器,匹配class属性中包含特定类的元素
element 标签选择器
P>C 组合选择器,子元素选择器,匹配P元素的所有子元素中为C的元素
E[attr] 属性选择器,匹配所有具有属性attr的元素
E::before 伪元素选择器,在E元素之前插入生成的内容
E:first-child 伪类选择器, 匹配父元素的第一个子元素

选择器的优先级是怎样的?对于复杂场景如何计算优先级?

  1. 从高到低
  1. 复杂场景计算优先级
    划分成四类,根据abcd的数量来计算优先级。优先选择包含a数量最多的那个,若a数量相同,则选择b数量最多,以此类推。

a:link, a:hover, a:active, a:visited 的顺序是怎样的? 为什么?

建议顺序为:

a:link { /*未被点击*/
  color: #000;
}
a:visited { /*已被点击*/
  color: #CCC;
}
a:hover { /*鼠标在链接上*/
  color: #0FF;
}
a:active { /*鼠标按下,但还没有释放*/
  color: #FFF;
}

CSS后面生效的会覆盖前面的。因此为了保证能显示出 hover 和 active 的效果,要把这两个放在后面,active 要在 hover 后面。

以下选择器分别是什么意思?

#header{ /*id选择器,匹配id值为header的元素*/
}
.header{ /*class选择器,匹配所有class值为header的元素*/
}
.header .logo{ /*匹配class值为header元素的所有class值为logo的后代*/
}
.header.mobile{ /*匹配class值同时包含header和mobile的元素 */
}
.header p, .header h3{ /*匹配class值为header元素后代中的p或者h3元素*/
}
#header .nav>li{ /*匹配id值为header元素后代中.nav元素中的直接后代li
 */
}
#header a:hover{ /*匹配id值为header元素后代中的a元素指定鼠标移动到其上方的样式 */
}
#header .logo~p{ /*匹配id值为header的元素后代中.logo元素之后的同级p元素*/
}
#header input[type="text"]{/*匹配id值为header的元素后代中 type 属性为 text 的input元素*/
}

列出你知道的伪类选择器

div:first-child和div:first-of-type的作用和区别

div:first-child: 匹配父元素下的第一个子元素,且标签为div。
div:first-of-type: 匹配父元素下的第一个标签为div的元素。

运行如下代码,解析下输出样式的原因。

<style>
.item1:first-child{
  color: red;
}
.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>
Paste_Image.png

.item1:first-child{ color: red;} : 匹配父元素的第一个子元素并且该元素的 class 为 item1。<p class="item1">aa</p> 符合匹配。aa 字体为红色。
.item1:first-of-type{ background: blue;} 匹配父元素下的同种标签的第一个且该元素的 class 为 item1。<p class="item1">aa</p><h3 class="item1">bb</h3>符合匹配。背景为蓝色。

上一篇下一篇

猜你喜欢

热点阅读