CSS选择器

121 阅读1分钟

css选择器

<style>
    p {
        color : 颜色
        font : 字体
     } 
<style>

选择器:根据不同的需求吧不同的标签选出来,选择标签用的 选择器分为基础选择器和复合选择器 基础选择器:由单个选择器组成 复合选择器:包括标签选择器,类选择器,id选择器和通配符选择器


标签选择器

标签选择器:将html页面的标签名称作为选择器,按标签名分,为页面的某一指定标签设置统一的css样式,一般不推荐,因为这样是全部的某一标签全部指定了样式的

语法:

<style>
    标签名 {
    属性1:属性值1;
    属性2:属性值2;
    属性3: 属性值3;
    ···
    }
</style>

类选择器

如果想要差异化的选择不同的标签,单独选一个或者几个标签,可以使用类选择器 语法:

<style>
.类名 {
    属性1:属性值1;
    属性2:属性值2;
    属性3: 属性值3;
    ···
</style>
}

结构需要用class属性来调用,例如

.red {
    color: red
}
<div class='red'> 红色字体 </div>
.redd { color: red }

此时,上面div标签里面的"红色字体"四个字就会变为红色 口诀: 样式点定义:由.+类名来定义样式 结构类调用:想要定义某种格式,就有某个标签的类class属性来调用该选择器 一个或多个,开发最常用 可以有多类名,即一个class属性里面有多个类名,用空格隔开 使用多类名的意义: 1·有些属性可以共性抽取为一个类选择器里面的样式 2·可以减小代码冗余 3·当要修改某一特性的属性时,方便修改

举例:用类选择器制造一个盒子

代码为
<style>
    .green {
        width: 100px;
        height: 100px;
        background-color: green;
        
    }
    .blue {
        width: 100px;
        height: 100px;
        background-color: blue; 
    }
</style>
<div class="green">绿色</div>
<div class="blue">蓝色</div>
<div class="green">绿色</div>

也可以写为
<style>
    .box {
        width: 100px;
        height: 100px;
        font-size: 30px
    }
    .green {
       
        background-color: green;
        
    }
    .blue {
        
        background-color: blue; 
    }
</style>
<div class="green box">绿色</div>
<div class="blue box">蓝色</div>
<div class="green box">绿色</div>

.green { width: 100px; height: 100px; background-color: green; } .blue { width: 100px; height: 100px; background-color: blue; }
绿色
蓝色
绿色

.box { width: 100px; height: 100px; font-size: 30px } .green { background-color: green; } .blue { background-color: blue; }
绿色
蓝色
绿色

id选择器

id选择器可以为特定id的html元素指定特定的样式 html元素的id属性来设置id选择器,css中id选择器用‘#’来定义 id只能被使用一次 语法

    #id名{
        属性1: 属性值1;
        ···
    }

例如:将id为nav元素中的内容设置为红色

<style>
    #nav {
    color:pink;
}
</style>

<div id="nav"> maoguo </div>
maoguo就会变为粉红色
#nav { color:pink; }
maoguo

通配符选择器

在css中,通配符选择器使用"*"定义,它选取页面中所有的元素(标签) 语法:

* {
    属性1: 属性值1;
    ···
}
例如:
<style>
* {
    color: red;
}
</style>

将页面所有的字体颜色改为红色