【css笔记(2)】如何给元素应用规则?

css选择器

在介绍之前我么你先来看看css大致分为几种选择器:

1.类型选择器(元素选择器)

2.后代选择器(元素的所有后代)

3.伪类(:active, :hover, :focus, :link, :visited, :first-child, :lang)

4.通用选择器(*)

5.子选择器(元素的直接后代)

6.相邻同胞选择器(同一父元素下该元素之后的某元素)

7.属性选择器

上面讲的太抽象?没事,举个例子,如下页面1.html结构:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1.html</title>
    <style>
        #content div#main-content h2{
            color: gray;
        }
        #content #main-content>h2{
            color: blue;
        }
        body #content div[id="main-content"] h2{
            color: green;
        }
        #main-content div.news-story h2{
            color: orange;
        }
        #main-content [class="news-story"] h2{
            color: yellow;
        }
        div#main-content div.news-story h2.first{
            color: red;
        }
    </style>
</head>
<body>
    <div id="content">
        <div id="main-content">
            <h2>Strange Times</h2>
            <p>Here you can read bizarre news stories from around the globe</p>
            <div class="news-story">
                <h2 class="first">
                    Bog Snorkeling Champion Announced Today
                </h2>
                <p>
                    The 2008 Bog Snorkelinig Championship was won by Conor Murphy with an impressive time of 1 minute 38 seconds
                </p>
            </div>
        </div>
    </div>
</body>
</html>

则对应的选择器分别有:

1.类型选择器 div{color: red;} 
2.后代选择器 #content div{background: #ccc;} 
3.伪类 p:first-child{padding: 2px;} 
4.通用选择器(*) *{margin: 0;} 
5.子选择器 #content>div{font-size: 14px;} 
6.相邻同胞选择器 h2 + p{width: 200px;} 
7.属性选择器 div[id="content"]{border: 2px solid #fff;} 

css层叠和特殊性

当某一元素应用多种css规则时元素选取那种样式呢?,css会通过层叠处理这种冲突.层叠会没每个规则赋予一个重要度,重要度高的规则会覆盖重要度低的规则.层叠采用以下重要度次序:

1.标有!important的用户样式

2.标有!important的作者(站点开发者)样式

3.作者(站点开发者)样式

4.用户样式

 

然后通过选择器的特殊性来决定规则的次序.如何计算特殊性?我们将选择器的特殊性由高到低分为4个等级.应用于下面四个规则:

1.a为行内样式(内联样式),若有则为1000,没有则为000,a*1000

2.bid选择器的数量乘100,b*100

3.c为类,伪类和属性选择器的数量乘10,c*10

d为元素选择器和伪元素选择器的数量乘1,d*1

元素的特殊性值(w=a*1000+b*100+c*10+d)后选取特殊性值最大的应用元素

我们还以上面的1.html页面为例:

得到图中的表,所以应用样式后的页面在浏览器中显示为:

伪类和伪元素

在我刚学习的时候经常讲伪类和伪元素搞混,它们是不一样的.

伪类

伪类

:active

向被激活的元素添加样式

:focus

向拥有键盘输入焦点的元素添加样式

:hover

当鼠标悬浮在元素上方时,向元素添加样式

:link

向未被访问的链接添加样式

:visited

向已被访问的链接添加样式

:first-child

向元素的第一个子元素添加样式

:lang

向带有指定lang属性的元素添加样式

 这是伪元素

伪元素

:first-letter

向文本的第一个字母添加特殊样式表

:first-line

向文本的首行添加样式

:before

在元素之前添加内容

:after

在元素之后添加内容

原文地址:https://www.cnblogs.com/libra-yong/p/6830117.html