CSS篇-样式表、选择器、权重、伪类

CSS定义

CSS:Cascading Style Sheet(层叠样式表)

// 写法
选择器 {
    属性名: 属性值;
}

CSS样式表

(1)三种样式表使用

// 内联样式
<div style=" 100px; height: 100px;"></div>

// 内部样式表
<style type="text/css">
    div {
        width: 100px;
        height: 100px;
    }
</style>

// 外部样式表
<link rel="stylesheet" type="text/css" href="">

(2)三种样式表的权重和优先级

内联样式 > 内部样式表 > 外部样式表

选择器

(1)6大基础选择器

// 1、id选择器:唯一对应
<div id="box"></div>
<style type="text/css">
    #box {
        color: red;
    }
</style>

// 2、类class选择器:统一类
<div class="box"></div>
<style type="text/css">
    .box {
        color: red;
    }
</style>

// 3、标签选择器:初始化标签使用
<div></div>
<style type="text/css">
    div {
        color: red;
    }
</style>

// 4、*通配符标签
<style type="text/css">
    * {
        margin: 0;
    }
</style>

// 5、属性选择器:表单中input常用
<div id="box1"></div>
<a href="http://www.baidu.com"></a>
<style type="text/css">
    [id="box"] {
        color: red;
    }
    [href] {
        text-decoration: none;
    }
</style>

// 6、最高优先权
<style type="text/css">
    div {
        background: red !important;
    }
</style>

(2)6大基础选择器优先级

!important > id > class | 属性 > 标签 > *

(3)复合选择器

// 1、派生选择器(父子选择器),从右到左匹配。包含两种:包含选择器和子选择器
<header>
    <p>
        <em>你好</em>
    </p>
</header>
<style type="text/css">
    /*包含选择器*/
    header p em {
        color: red;
    }

    /*子选择器:必须层层父子级*/
    header > p > em {
            color: red;
        }
    /*直接父子选择器*/
        p > em {
            color: red;
        }
</style>

// 2、相邻兄弟选择器:1、同父级;2、相邻;3、在其之后
<p>这里是第一个P标签</p>
<h2 class = 'h2'>标题H2</h2>
<p>这里是第一个P标签(变色)</p>
<p>这里是第二个P标签</p>
<style type="text/css">
    .h2 + p{
        color: red;
    }
</style>

// 3、兄弟选择器~(匹配选择器)
<p>这里是第一个P标签</p>
<h2 class = 'h2'>标题H2</h2>
<p>这里是第一个P标签(变色)</p>
<p>这里是第二个P标签(变色)</p>
<style type="text/css">
    .h2 ~ p{
        color: red;
    }
</style>

// 4、并列选择器
<h1 class="title">你好!</h1>
<style type="text/css">
    h1.class { 
        color: pink;
    }
</style>

// 5、分组选择器
<input type="text" />
<br />
<textarea cols="3" rows="10"></textarea>
<style type="text/css">
    input,
    textarea {
        outline: none;
    }
</style>

CSS权重(256进制)计算规则

(1)分类权重

  • *:0
  • 标签、伪元素:1
  • class、属性、伪类 :10
  • id:100
  • 内联样式:1000
  • !important:正无穷

(2)计算示例

// 基础选择器优先级
正无穷 > 100 >10 >1 >0
!important > id > class | 属性 > 标签 > *

// 权重计算
<div id="div_id" class="div_class">
    <h1 id="h1_id" class="h1_class">
        你好!
    </h1>
</div>
<style type="text/css">
    #div_id h1 { 
        color: pink; // 100 + 1
    }
    .div_class .h1_class {
        color: purple; // 10 + 10
    }
    .div_class #h1_id.h1_class { // 10 + 100 + 10
        color: red;
    }
</style>

伪类和伪元素

  1. CSS2中伪类和伪元素都是要单冒号(:)
  2. CSS3中伪类使用单冒号(:),伪元素使用双冒号(::)

伪类参考
伪元素参考

原文地址:https://www.cnblogs.com/aibabel/p/11250985.html