search
HomeWeb Front-endHTML TutorialCSS选择器之:nth-child(n)与:nth-last-of-type(number)_html/css_WEB-ITnose

这段时间在做一些东西,整理了其中遇到的一个关于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>

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

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

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

第一个与最后一个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;}

嗯?怎么回事, 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> 

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

.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;}

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

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

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

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

偶数:

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

其实还有一个能达到上图这种效果,也就是 :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的奇数元素}

偶数:

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

测试一下:

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

最终效果:

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

Statement
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
The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),