CSS选择器
2019-03-13 本文已影响0人
如梦初醒Tel
常见的CSS选择器
基础选择器
通配符选择器
* {
margin: 0;
padding: 0;
}
一般放在css开头
id选择器
通过设置元素的 id
属性为该元素制定ID。ID名由开发者指定。每个ID在文档中必须是唯一的。
一般用于重要的模块或者重要的区块,在写样式表时,用(#
)表示
#div1{
height:200px;
width:200px;
background:red;
}
类选择器
通过设置元素的 class
属性,可以为元素指定类名。类名由开发者自己指定。 文档中的多个元素可以拥有同一个类名。
在写样式表时,类选择器是以英文句号(.
)开头的。
<style>
.first {
font-weight: bold;
color:grey;
}
.second {
font-size: 20px;
color:red;
}
.currency{
text-decoration: line-through;
}
</style>
<ul>
<li class="first currency">菜单1</li>
<li class="second currency">菜单2</li>
</ul>
标签选择器
div{
font-size:20px;
}
p{
color:red;
}
组合选择器
-
A, B
多元素选择器(,
)用,分隔,同时匹配元素A或元素B
.big, .small {
position: absolute;
}
-
A B
后代选择器,用空格分隔,匹配A元素所有的后代(不只是子元素、子元素向下递归)元素B
<style>
.first .third{
color:red;
}
</style>
<div class="first">第一层
<div class="second">第二层
<div class="third">第三层
<div class="four">最后层
</div>
</div>
</div>
</div>

-
A > B
选中匹配 B 且为匹配 A 的元素的直接子元素。
.first > .second > .third{
color:red;
}


因为first的子元素是second ,之后才是third,而上图中,直接选first,之后选third,所以找不到,因为third是second的直接子元素,不是first的直接子元素。
属性选择器
-
[attr]
选择包含 attr 属性的所有元素,不论 attr 的值为何。
<html>
<head>
<style>
[title]{
color:red;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<h2 title="Hello world">Hello world</h2>
<a title="傻的可爱">你好,我是中国人</a>
<hr />
<h1>无法应用样式:</h1>
<h2>Hello world</h2>
<a href="#">不好,你是小日本</a>
</body>
</html>

-
[attr=val]
仅选择 attr 属性被赋值为 val 的所有元素。
<html>
<head>
<style>
a[name]{
color:red;
font-size:30px;
text-decoration: line-through;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<a name="傻子">小日本</a>
<hr />
<h1>无法应用样式:</h1>
<a href="#">Hello</a>
</body>
</html>

伪类选择器
<html>
<head>
<style>
.child:first-child {
color: red;
}
.child:first-of-type {
background: green;
}
.child :first-child {
font-size:60px;
}
.child :first-of-type {
color:blue;
}
.child:last-child{
color:red;
}
</style>
</head>
<body>
<div class="father">
<div class="child">
div1.child
</div>
<p class="child">p1.child</p>
<div class="child">
div2.child
</div>
<div class="child">
<div class="item">
div3.child.item
</div>
<p class="item">div3.p.item</p>
</div>
<p class="child">p2.child</p>
</div>
</body>
</html>

.child:first-child
匹配第一个class=child 的子元素,字体为红色
.child:first-of-type
匹配class=child 使用同种标签的第一个子元素,这个意思就是说选中div和p这两个标签中第一个子元素,颜色为绿色
.child :first-child
这个和第一个的区别是 .child
后面跟(:
)之间有一个空格,表示匹配父元素class=child下第一个子元素,字体变大
.child :first-of-type
表示匹配父元素class=child下使用同种标签的第一个子元素,所以父元素div=child这个标签下 第一个使用的div标签和p标签颜色为蓝色
.child:last-child
表示匹配最后一个child子元素
注意child和:之间的空格,是否有空格的含义不同
伪元素选择器
所有的伪元素
<html>
<head>
<style type="text/css">
.p1:first-line {
color: #ff0000;
font-variant: small-caps
}
.p2:first-letter{
color: #ff0000;
font-size:xx-large
}
</style>
</head>
<body>
<p class="p1">
小日本该死
</p>
<p class="p2">
小日本该死
</p>
</body>
</html>

选择器的优先级别
- 在属性后面使用 !important 会覆盖页面内任何位置定义的元素样式
- style内联样式
- id选择器
- 类选择器
- 伪类选择器
- 属性选择器
- 标签选择器
- 通配符选择器
- 浏览器自定义