前言
本文主要介绍CSS选择器的用法
CSS选择器主要分为基础选择器和符合选择器,我们一起来看一下两者的具体内容吧。为了方便演示此处使用的全部是内部样式
基础选择器
1.标签选择器
标签名{}
<body>
<a>hello,大饼</a><!--a标签-->
<p>hello,大饼</p><!--p标签-->
<style>
a {/*选择a标签中的内容*/
font-size: 100px;/*设置文字大小为100px*/
color: red;/*设置文字颜色为红色*/
}
p{/*选择p标签中的内容*/
font-size: 30px;/*设置文字大小为30px*/
color: darkgreen;/*设置文字颜色为darkgreen*/
}
</style>
</body>
页面显示:
注意事项:
能快速为同一类型的标签都选择出来.
但是不能差异化选择
2.类选择器
.类名{}
CSS 中使用 . 开头表示 id 选择器
<div class="hello">hello,大饼,类选择器</div><!--hello类-->
<div class="hi">hello,大饼,类选择器</div><!--hi类-->
<style>
.hello {/*选择hello类中的内容*/
font-size: 100px;/*设置文字大小为100px*/
color: red;/*设置文字颜色为红色*/
}
.hi{/*选择hi类中的内容*/
font-size: 30px;/*设置文字大小为30px*/
color: darkgreen;/*设置文字颜色为darkgreen*/
}
</style>
页面显示:
注意事项:
1.class 来命名类.
2.类名选择用 . 开头的
3.如果是长的类名, 可以使用 - 分割.
4.不要使用纯数字, 或者中文, 以及标签名来命名类名.
5.一个标签可以同时使用多个类名,如:
<div class="hello"></div>
<div class="hi"></div>
3.id 选择器
#id名{}
CSS 中使用 # 开头表示 id 选择器
<div id="hello1">hello,大饼,id选择器</div>
<!--id为hello1-->
<style>
#hello1{/*选择id为hello1中的内容*/
font-size: 30px;/*设置文字大小为30px*/
color: darkgreen;/*设置文字颜色为darkgreen*/
}
</style>
页面显示:
注意事项:
id 选择器的值和 html 中某个元素的 id 值相同
html 的元素 id 不必带 #
id 是唯一的, 不能被多个标签使用
4.通配符选择器
*{}
使用 * 的定义, 选取所有的标签.
<div >hello,大饼,通配符选择器</div>
<div >hello,大饼,通配符选择器</div>
<div >hello,大饼,通配符选择器</div>
<div >hello,大饼,通配符选择器</div>
<style>
*{
font-size: 60px;
color: salmon;
}
</style>
页面显示:
总结:
标签选择器: 能选出所有相同标签 不能差异化选择
类选择器: 能选出一个或多个标签 根据需求选择, 最灵活, 最常用.
id 选择器: 能选出一个标签 同一个 id 在一个 HTML 中只能出现一次
通配符选择器: 选择所有标签 特殊情况下使用
复合选择器
1.后代选择器
选择某个父元素中的某个子元素.
元素1 元素2{}
<hello>
<d1>hello,大饼1</d1>
<d2>hello,大饼2</d2>
<d3>hello,大饼3</d3>
</hello>
<hi>
<d4>hello,大饼4</d4>
<d5>hello,大饼5</d5>
<d6>hello,大饼6</d6>
</hi>
<style>
hello d2{
font-size: 50px;
color: rgb(192, 13, 202);
}
hi d4{
font-size: 60px;
color: rgb(13, 161, 144);
}
*{
font-size: 70px;
color: rgb(0, 0, 0);
}
</style>
页面显示:
元素 2 不一定非是 儿子, 也可以是孙子.
可以是任意基础选择器的组合. (包括类选择器, id 选择器)
2.子选择器
元素1>元素2 { }
使用大于号分割
只选亲儿子, 不选孙子元素
和后代选择器类似, 但是只能选择子标签
3.并集选择器
元素1, 元素2 { }
通过 逗号 分割等多个元素.
表示同时选中元素 1 和 元素 2
任何基础选择器都可以使用并集选择器.
并集选择器建议竖着写. 每个选择器占一行. (最后一个选择器不能加逗号)
4.伪类选择器
(1)链接伪类选择器
a:link
选择未被访问过的链接
a:visited
选择已经被访问过的链接
a:hover
选择鼠标指针悬停上的链接
a:active
选择活动链接(鼠标按下了但是未弹起)
<a href="https://www.bilibili.com/">哔哩哔哩</a>
<style>
a:link {
color: rgb(22, 158, 180);
text-decoration: none;
font-size: 50px;
/* 去掉 a 标签的下划线 */
}
a:visited {
color: green;
font-size: 40px;
}
a:hover {
color: rgb(110, 47, 98);
font-size: 30px;
}
a:active {
color: salmon;
font-size: 20px;
}
</style>
页面显示:
清空浏览器历史记录让链接变成为访问过的样子: ctrl + shift + delete
(2):force 伪类选择器
选取获取焦点的 input 表单元素
<div class="three">
<input type="text">
<input type="text">
</div>
<style>
.three>input:focus {
color: rgb(89, 99, 210);
}
</style>
页面显示:
后代选择器 :选择后代元素 ,可以是孙子元素
子选择器: 选择子元素 只能选亲儿子, 不能选孙子
并集选择器: 选择相同样式的元素
链接伪类选择器: 选择不同状态的链接
:focuse: 伪类选择器 选择被选中的元素