1.选择器是CSS中的关键部分,它允许针对特定元素或一组元素定义样式。
2.常用选择器:
·元素选择器:如在head中直接对h1进行修改,最基本的选择器。
·类选择器 .:对类名为highlight的元素进行相应处理。
PS:如何理解类?
类(Class)允许将一组样式规则关联到一个名称上,然后在HTML中通过这个名称来引用这组样式。
·ID选择器 #:对ID为header(自行定义)的元素进行修改
以上三个为最常用的三个选择器类型。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS选择器</title>
<style>
/*元素选择器*/
h1{
color:blue;
}
/*类选择器*/
.highlight{
background-color:aquamarine;
}
/*ID选择器*/
#header{
font-size:larger;
}
</style>
</head>
<body>
<h1>这是一个元素选择器示例</h1>
<h3 class="highlight">这是一个类选择器示例</h3>
<h3>这是另一个类选择器示例</h3>
<h3 id="header">这是一个ID选择器示例</h3>
</body>
</html>
tips:ctrl+shift+/ 快速注释
·通用选择器 *:选择所有元素。如下,将全部字体改为楷体。
*{
font-family:KaiTi;
}
3.较复杂的选择器
·子元素选择器:选择直接位于父元素内部的子元素。类似于嵌套
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>CSS选择器</title>
<style>
/*子元素选择器*/
.father >.son{
color:cornflowerblue;
font-weight:bolder;
}
</style>
</head>
<body>
<div class="father">
<p class="son">这是一个子元素选择器示例</p>
</div>
</body>
</html>
·后代选择器
<!DOCTYPE html>
<html>
<head>
<style>
/*子元素选择器*/
.father >p{
color:cornflowerblue;
font-weight:bolder;
}
</style>
</head>
<body>
<div class="father">
<p class="son">这是一个子元素选择器示例</p>
<div>
<p class="grandson">这是一个后代选择器示例</p>
</div>
</div>
</body>
</html>
只把father的子元素添加了字体颜色,而其包含的div中的p标签未被标记,因为子代不等于后代。grandson不是子代而是后代。如下
<html>
<head>
<style>
/*子元素选择器*/
.father >p{
color:cornflowerblue;
font-weight:bolder;
}
/*后代选择器*/
.father p{
color:crimson;
font-size:xx-large;
}
</style>
</head>
<body>
<div class="father">
<p class="son">这是一个子元素选择器示例</p>
<div>
<p class="grandson">这是一个后代选择器示例</p>
</div>
</div>
</body>
</html>
我们可以发现,后代的颜色将子代原本的蓝色覆盖了,如何恢复本身颜色呢?选择器优先级如下,ID>类>标签名。所以若把p标签恢复为.son即可保持原有颜色。
<style>
/*子元素选择器*/
.father >.son{
color:cornflowerblue;
font-weight:bolder;
}
/*后代选择器*/
.father p{
color:crimson;
font-size:xx-large;
}
</style>
但是我们还可以发现,虽然子元素的字体颜色等样式恢复了,但是字体大小依旧按照后代选择器的大小输出,所以我们可以依此知道,子代选择器优先级高于后代选择器(因无论类的优先级与否,之前颜色、字体大小均被覆盖)。
·相邻元素选择器:会选择同一级别下的元素中的紧跟选中元素之后的第一个p标签。
<head>
<style>
/*相邻元素选择器*/
h3 + p{
background-color:darksalmon;
}
</style>
</head>
<body>
<p>这是一个普通的p标签</p>
<h3>这是一个相邻兄弟选择器示例</h3>
<p>这是另一个普通的p标签</p>
</body>
·伪类选择器: 选择HTML文档元素特定状态或者位置的,不仅仅是元素本身的属性。通常给用户交互文档结构,或者其他条件下的元素应用样式。(当鼠标放在上面时提供不同的交互方式)
......
#element:hover{
background-color:fuchsia;
}
<h3 id="element">这是一个伪类选择器示例</h3>
......
·伪元素选择器(新手不常用):创建一个虚拟元素并样式化他们。如::after(在之后插入虚拟内容)