这是一个在代码编写过程中,发现错误的一篇文章。这本是一个简单的问题,但被自己的逻辑思维绕进了死胡同,所以记录下来,以免犯同样的错误。
首先记录一下使用到的几个选择器:
-
结构伪类选择器之一X:nth-child(n)
匹配顺序中第n个元素,例如,ul下有5个li标签,li:nth-child(3){…},表示匹配到第三个li标签,为其设置样式。 -
结构性伪类选择器之一 X:last-child
该选择器是匹配父元素中的最后一个子元素。例如,ul下有5个li标签,使用选择器设置样式时,则是 li:last-child{…},表示匹配到ul中的最后一个li标签,为其设置样式。 -
属性选择器之一 X[属性名=“属性值”]
表示匹配到X元素,且该元素的属性名=“属性值”。例如,有两个a标签,
在这里插入代码片<a href="1">第一个</a> <a href="2">第二个</a>
,使用属性选择器a[href=‘2’]{…},表示匹配的就是a标签中,且属性名是href且属性值是2的a标签,为其设置样式。
该错误就是在写导航栏的时候,使用了last-child选择器,无法实现单独为最后一个a标签设置样式。
a:last-child{background-color: blue;}
此方法是不能实现给最后一个a单独设置样式的,在下列每个a都是父元素li中的唯一的一个,且同样也是最后一个,这样写的话,其实相当于是给每个a都设置该样式。
下面是错误css样例:
<style>
ul{
width: 891px;
height: 111px;
margin: 0 auto;
background-color: aquamarine;
}
li{
list-style: none;
float: left;
}
a {
height: 111px;
float: left;
text-align: center;
line-height: 111px;
margin-right: 34px;
font-family: '微软雅黑' ;
font-size: 22px;
}
/* 此方法是不能实现给最后一个a单独设置样式的,在下列li中每个a都是li中的最后一个,
因为每个li中仅有一个a,这样写的话,其实相当于是给每个a都设置该样式。 */
a:last-child{
background-color: blue;
}
</style>
如果想单独给最后一个a设置样式,可以使用指定的属性选择器,或给标签单独设置class名称。(注意权重问题),在下面的完整代码中,两种方法皆已写在其中,在实际书写中,二者选择其一即可。
完整的正确代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
ul{
width: 891px;
height: 111px;
margin: 0 auto;
background-color: aquamarine;
}
li{
list-style: none;
float: left;
}
a {
height: 111px;
float: left;
text-align: center;
line-height: 111px;
margin-right: 34px;
font-family: '微软雅黑' ;
font-size: 22px;
}
/* 如果想单独给最后一个a设置样式,可以使用属性选择器或者单独设置class名称 */
/* 第一种方法:单独设置class名称 */
/* .end{
background-color: blue;
} */
/* 第二种方法:使用指定的属性选择器 */
a[href="123"]{
background-color: blue;
}
</style>
</head>
<body>
<ul>
<li><a href="#">首页</a></li>
<li><a href="#">网站开发</a></li>
<li><a href="#">安卓开发</a></li>
<li><a href="#">案例中心</a></li>
<li><a href="#">文章中心</a></li>
<li><a href="#">联系我们</a></li>
<li><a href="#">关于我们</a></li>
<li><a class="end" href="123">旧版</a></li>
</ul>
</body>
</html>
其实单独设置样式有很多且简单的方法,但本篇纯属于记录自己学习过程中的错误,他人勿喷。
---------------------------------2021年6月23日更---------------------------------------------------------------------------
今天在使用中,忽然想起来还有一个最简单的方法,就是把选择器写给li,后面再写a标签,同样也可以实现效果。人果然是不在死胡同里的时候,才能聪明一些,被自己蠢笑了。
/* 第三种方法 */
ul li:last-child a{
background-color: blue;
}