Table of Contents
:nth-child(n)定义和用法
:nth-child(n)更多设置:
:nth-last-of-type(number)定义和用法
:nth-last-of-type(number)更多设置
Home Web Front-end HTML Tutorial CSS选择器之:nth-child(n)与:nth-last-of-type(number)_html/css_WEB-ITnose

CSS选择器之:nth-child(n)与:nth-last-of-type(number)_html/css_WEB-ITnose

Jun 24, 2016 am 11:21 AM

这段时间在做一些东西,整理了其中遇到的一个关于CSS选择器的问题。

需要完成一个下图的侧边栏效果:

乍一看,很简单嘛,标签列表、弹框,完工!

然后我就写了如下代码:

<ul class="tag radius-8">    //标签    <li class="a"> code </li>    <li class="a"> code </li>    <li class="a"> code </li>    <li class="a"> code </li>    <li class="a"> code </li>        //弹框    <div class="secondary-tag-container radius-8" id="second-tag-div1">        <!-- 弹出层内容区域 -->        <div class="secondary-content radius-8" id="secondary-content1">                 <!-- 二级标签 -->                 <div class="second-tag">                       <li class="b"> code </li>                       <li class="b"> code </li>                       <li class="b"> code </li>                       <li class="b"> code </li>                       <li class="b"> code </li>                       <li class="b"> code </li>                 </div>                                                    <!-- 跳转按钮container -->                 <div class="skip-btn-container">                      <!-- 跳转按钮 -->                      <a class="skip-btn">Done</a>                 </div>         </div>                              </div> </ul>
Copy after login

基本样式OK了,然后添加:hover等效果:

.primary-tag:hover {    background-color: #F5F5F5;}
Copy after login

等等,这时候好像发现些什么:

第一个与最后一个li标签悬停时背景溢出了,没关系,so eazy:

.tag li:first-child {    border-top-left-radius: 8px;    border-top-right-radius: 8px;}.tag li:last-child {    border-bottom-left-radius: 8px;    border-bottom-right-radius: 8px;}
Copy after login

嗯?怎么回事, first-child 生效了, last-chilld 没有生效:

仔细思考了一下这两个选择器,发现:

  • li:first-child 是匹配父元素的第一个li元素

  • li:last-child 是匹配父元素的最后一个li元素

原来,因为弹框里面也存在 li 元素,所以 last-child 属性匹配到了弹框里面的最后一个 li ,在不修改 HTML 的基础上稍作修改:

  • li.a:first-child

  • li.a:last-child

这回总可以了吧,怀揣着希望,摁下了F5,我的天哪,还是原样,一脸懵逼中~~~

仔细查了下资料:

  • li.a:first-child 匹配父元素中class为a的,且是第一个li

  • li.a:last-child 匹配父元素中class为a的,且是最后一个li

也就是说,最后一个li如果class为a, last-child 生效;否则不生效(这里最后一个li还是匹配的弹框里的li,因为没有class为a,所以选择器失效,不会选中任何元素)。

许多人说:”仅通过CSS是无法实现的,需要通过jQuery.....省略一大段理由”(建立在不更改html结构标签的基础上),难道真的一个这么简单的效果无法通过CSS实现吗?

如果说不可以通过CSS实现,那一定是没有好好了解全CSS的属性选择器。功夫不负有心人,找到了 :nth-child(n) 选择器。

:nth-child(n)定义和用法

:nth-child(n) 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型,从第一个子元素开始计数(第一个子元素的下标是 1,不要和JS混淆,JS是0)。

n 可以是数字、关键词或公式。

例: li:nth-child(2)指定为ul下第二个li

  <ul>    <li><a></a></li>    <li><a></a></li>    <li><p><p></li>  </ul> 
Copy after login

所以,按照如下设置就能达到我们想要的效果:

.a:nth-child(1) {    border-top-left-radius: 8px;    //匹配第1个class为a的元素    border-top-right-radius: 8px;}.a:nth-child(5) {    border-bottom-left-radius: 8px;  //匹配第5个class为a的元素    border-bottom-right-radius: 8px;}
Copy after login

:nth-child(n)更多设置:

Odd 和 even 是可用于匹配下标是奇数或偶数的子元素的关键词。

在这里,我们为奇数 a 元素指定两种不同的背景色,从最后一个子元素开始计数:

.a:nth-child(Odd) {    color: #45E0B1;            //匹配class为a的奇数元素}
Copy after login

偶数:

.a:nth-child(even) {    color: #45E0B1;            //匹配class为a的偶数元素}
Copy after login

其实还有一个能达到上图这种效果,也就是 :nth-last-of-type(n) 选择器。

:nth-last-of-type(number)定义和用法

:nth-last-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素的每个元素,从最后一个子元素开始计数(第一个子元素的下标是 1,不要和JS混淆,JS是0)。

n 可以是数字、关键词或公式。

:nth-last-of-type(number)更多设置

Odd 和 even 是可用于匹配下标是奇数或偶数的子元素的关键词。

在这里,我们为奇数 a 元素指定两种不同的背景色,从最后一个子元素开始计数:

.a:nth-last-of-type(Odd) {    color: #45E0B1;            //匹配class为a的奇数元素}
Copy after login

偶数:

.a:nth-last-of-type(even) {    color: #45E0B1;            //匹配class为a的偶数元素}
Copy after login

测试一下:

.a:nth-last-of-type(5) {    color: #45E0B1;            //匹配class为a的从后往前数的第5个元素(也就是第一个)}.a:nth-last-of-type(1) {    color: #26D7D7;            //匹配class为a的从后往前数的第1个元素(也就是最后一个)}
Copy after login

最终效果:

其实很多时候,并不是没有解决办法或者说简便的办法,只是我们不知道,说明还懂得不够,需要学习来充实自己。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

See all articles