×

CSS选择元素中除最后一个之外的所有子元素:not(:last-child)

作者:Terry2019.09.29来源:Web前端之家浏览:15331评论:2
关键词::not:last-child

在设计和开发Web应用程序时,有时我们需要选择除最后一个元素之外的元素内的所有子元素,那么如何使用CSS来选择元素中除最后一个之外的所有子元素?

要使用CSS选择元素中除最后一个之外的所有子元素,可以使用使用:not和:last-child选择器。

语法:

element:not(:last-child) { 
    // CSS样式
}

:not(selector) 选择器:用来匹配非指定元素/选择器的每个元素。

:last-child选择器:用来匹配父元素中最后一个子元素。

示例1:创建一个导航菜单,除最后一个元素外,菜单之间用右边框分隔

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style> 
        nav { 
            margin: 30px; 
        } 
        nav a { 
            text-transform: capitalize; 
            text-decoration: none; 
            color: rgba(222, 128, 27); 
            font-family: sans-serif; 
            font-size: 20px;
            padding: 10px 10px; 
            margin-top: 30px; 
            width: 150px; 
            text-align: center; 
            display: inline-block; 
        } 
        nav a:not(:last-child) { 
            border-right: 5px solid palevioletred; 
        } 
    </style> 
</head> 
  
<body> 
    <nav> 
        <a href="#">Home</a> 
        <a href="#">About</a> 
        <a href="#">Blog</a> 
        <a href="#">Articles</a> 
        <a href="#">Contact Me</a> 
    </nav> 
</body> 
  
</html>

示例2:创建导航菜单,除最后一个元素之外,其他菜单添加一些CSS属性。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style> 
	        nav { 
	            margin: 30px; 
	        } 
	        nav a { 
	            text-transform: capitalize; 
	            text-decoration: none; 
	            color: rgba(60, 60, 60); 
	            font-family: sans-serif; 
	            font-size: 20px;
	            padding: 10px 10px; 
	            margin-top: 30px; 
	            width: 150px; 
	            text-align: center; 
	            display: inline-block; 
	            border: 2px solid black; 
	            border-radius: 5px; 
	        } 
	        nav a:not(:last-child) { 
	            background-color:peachpuff; 
	            color: white;
	        } 
	    </style> 
</head> 
  
<body> 
    <nav> 
        <a href="#">Home</a> 
        <a href="#">About</a> 
        <a href="#">Blog</a> 
        <a href="#">Articles</a> 
        <a href="#">Contact Me</a> 
    </nav> 
</body> 
  
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/html80938120983098.html

网友评论文明上网理性发言 已有2人参与

发表评论:

评论列表