【温故知新】CSS学习笔记(选择器)

选择器(选择符)

目的是选择目标元素(选择标签用)。
这里我们介绍四种基础选择器。


1、标签选择器

之前的例子都属于标签选择器,可以把某一类的标签全部选择出来;


2、类选择器

上面点声明,下面class调用就可以了;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    .red {
        color: red;
    }
    </style>
</head>
<body>
    <div class="red">多类名</div>
    <div>多类名</div>
    <div>多类名</div>
    <div>多类名</div> 
    <p class="red">段落多类名</p>
    <p>段落多类名</p>
    <p>段落多类名</p>
    <p class="red">段落多类名</p>
    <div>多类名</div> 
</body>
</html>

类选择器里面还有一种情况是多类名选择器
一个标签里面只能有一个class属性,不可以插入多个class。
各个类名之间用空格来分隔。
类名顺序颠倒也没有影响。 
样式显示效果跟HTML元素中的类名先后顺序没有关系,受CSS样式书写的上下顺序影响(若存在样式冲突)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    .red {
        color: red;
    }
    .font20 {
        font-size: 20px;
        color: blue;
    }
    </style>
</head>
<body>
    <div class="red font20">多类名</div>
    <div>多类名</div>
    <div>多类名</div>
    <div>多类名</div> 
    <p class="red">段落多类名</p>
    <p>段落多类名</p>
    <p>段落多类名</p>
    <p class="red">段落多类名</p>
    <div>多类名</div> 
</body>
</html>

3、ID选择器 
W3C标准规定,在同一个页面内,不允许有相同名字的id对象出现,但是允许相同名字的class。
类选择器好比人的名字,是可以多次重复使用的,但是id选择器好比人的身份证号码,是唯一的,不允许重复使用。
两者最大的区别在于使用的次数上面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    #last {
        color: pink;
    }
    </style>
</head>
<body>
    <div>id选择器</div>
    <div>id选择器</div>
    <div>id选择器</div>
    <div id="last">id选择器</div>
</body>
</html>

4、通配符选择器
通配符选择器用“*”号表示,是所有选择器中作用范围最广的,能匹配页面中所有的元素。
在实际开发里面基本用不到该类选择器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    * {
        color: deeppink;
    }
    </style>
</head>
<body>
    <div>通配符选择器</div>
    <div>通配符选择器</div>
    <p>通配符选择器</p>
    <span>通配符选择器</span>
</body>
</html>
发布了2002 篇原创文章 · 获赞 3892 · 访问量 1021万+

猜你喜欢

转载自blog.csdn.net/zhongguomao/article/details/104370253