饥人谷技术博客

CSS选择器

2016-07-28  本文已影响0人  饥人谷_沈梦圆

1.CSS选择器常见的有几种?

①基础选择器

②组合选择器

③属性选择器

以某个属性作为选择依据(E[attr = value])
例:div[id = test],匹配 id = test 的 div

④伪类选择器

⑤伪元素选择器


2.选择器的优先级是怎样的?(下面从高到低排列)

ps1:如果两个选择器规权值是一样的,那优先级是后面的覆盖前面的
ps2:CSS选择器规则优先级很简单,每个选择器本身有优先级,越具体优先级越高
ps3:id选择器的权值 > class选择器的权值 > 标签选择器的权值


3.class 和 id 的使用场景(增加 name )?

引用:HTML name、id、class 的(格式/应用场景/特性)等区别介绍


4.使用 CSS 选择器时为什么要划定适当的命名空间?


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

#header{    /* 选择 id="header" 的元素 */
}
.header{   /* 选择 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" 下 class="nav" 中的所有 li 子元素*/
}
#header a:hover{  /* 选中 id="header" 下子元素鼠标悬停在 a 链接上时的样式设置*/
}

6.列出你知道的伪类选择器


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

first-child 定义匹配元素中第一个子元素,而 first-of-type 定义匹配父元素下使用同种标签的第一个子元素。下面我们给两个对比的例子:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <link href="css/style.css" rel="stylesheet">
        <style>
        .box>h1:first-of-type{
            text-align: center;
        }
        </style>
    </head>
    <body>
    <div class="box">
        <div>
            <h1>我是标题1</h1>
        </div>
        <h1>我的标题2</h1>
        <p>我的段落1</p>
    </div>
    </body>
</html>

上面这串代码我们用到了 :first-of-type 我们在浏览器中得到如下图的效果:

first-of-type.png
接下来我们将上面代码中的 :first-of-type 修改为 :first-child 我们得到下面这个效果,可以很明显的看到我们的命令并没有生效。 first-child(1).png

当我们将代码修改为这样的时候:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <link href="css/style.css" rel="stylesheet">
        <style>
        .box>h1:first-child{
            text-align: center;
        }
        </style>
    </head>
    <body>
    <div class="box">
        <h1>我的标题2</h1>
        <div>
            <h1>我是标题1</h1>
        </div>
        <p>我的段落1</p>
    </div>
    </body>
</html>

我们就可以得到我们想要的效果,如下图:

first-child(2).png

<strong>我们可以得到这样的结论,:first-of-type 会自动寻找 box 下的 h1 元素,无论中间穿插了多少别的元素;而 :first-child 它只能根据 box 中第一个子元素来进行命令,若第一个不是 h1 元素,则它就找不到 box 下的 h1 元素,命令无法生效。


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

<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>

代码效果图如下:

代码显示.png

9. text-align: center 的作用是什么,作用在什么元素上?能让什么元素水平居中

10.如果遇到一个属性想知道兼容性,在哪查看?

利用 can i use 即可查询


<strong>本文版权归作者和饥人谷所有,转载请注明出处

上一篇下一篇

猜你喜欢

热点阅读