AtoZ CSS截屏视频:nth-​​child和nth-of-type

Loading the player…
正在加载播放器…
here. 此处找到该系列的其他条目。

成绩单 (Transcript)

:nth-child is a pseudo class used to select elements by a numeric expression.

:nth-child是一个伪类,用于通过数字表达式选择元素。

The syntax is quite different to most other aspects of CSS and can be a bit tricky to get your head around, to begin with.

语法与CSS的大多数其他方面完全不同,因此从头开始可能会有些棘手。

In this episode we’ll look at:

在本集中,我们将研究:

  • the various ways of using :nth-child,

    各种使用方式:nth-child

  • the slightly more flexible :nth-of-type selector

    稍微更灵活的:nth-of-type选择器

  • and their counterparts selectors :nth-last-child and :nth-last-of-type.

    及其对应的选择器:nth-last-child:nth-last-of-type

:nth-child (:nth-child)

:nth-child selects child elements if their position in the document matches a pattern described by an algebraic expression.

:nth-child如果元素在文档中的位置与代数表达式描述的模式匹配,则选择元素。

The :nth-child selector looks a bit like this:

:nth-child选择器看起来像这样:

li:nth-child(expression); {}

The “expression” can either be the keywords even or odd, a whole number or a formula in the pattern of an+b where a and b are whole numbers – positive or negative.

“表达式”可以是关键字“ even或“ odd ,整数或an+b模式中an+b公式,其中ab是整数–正数或负数。

As :nth-child can be used to select a range of different elements under different circumstances, it’s difficult to explain how it works and what it’s for. Let’s look at a series of examples to illustrate its uses.

由于:nth-child可用于在不同情况下选择一系列不同的元素,因此很难解释它的工作原理和用途。 让我们看一系列示例以说明其用法。

I have an unordered list, with 12 list items. Let’s see how we can use :nth-child to match a specific item or pattern of items:

我有一个无序列表,有12个列表项。 让我们看看如何使用:nth-child来匹配特定项目或项目模式:

<ul> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li>  
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
  <li>lorem ipsum</li> 
</ul>

To select the third list-item, I could use li:nth-child(3).

要选择第三个列表项,我可以使用li:nth-child(3)

To select all the even items, I can use even keyword. Conversely, I can use :nth-child(odd) to select all the odd numbered items. These are commonly used selectors to stripe the background colour of alternate rows in a table of data.

要选择所有偶数项,我可以使用even关键字。 相反,我可以使用:nth-child(odd)选择所有奇数编号的项目。 这些是常用的选择器,用于去除数据表中交替行的背景色。

To select every third item, I can use li:nth-child(3n).

要选择每三个项目,我可以使用li:nth-child(3n)

To select the first 4 items, I can use li:nth-child(-n+4). To select everything except the first 4 items, I can use li:nth-child(n+5).

要选择前4个项目,我可以使用li:nth-child(-n+4) 。 要选择除前4个项目以外的所有内容,我可以使用li:nth-child(n+5)

an+b表达式 (The an+b expression)

We’ve seen how :nth-child(odd) can select all the odd numbered items in a list. An alternative approach to using the odd keyword is to use the expression 2n+1.

我们已经了解了:nth-child(odd)如何选择列表中所有奇数编号的项目。 使用odd关键字的另一种方法是使用表达式2n+1

But how does the expression work?

但是表达式如何工作?

When the expression, in the format an+b contains non-zero values for a and b, the child elements are split into groups of a elements.

当表达式以格式an+b包含ab的非零值时,子元素将拆分为a元素组。

If the expression was 2n+1, the child elements would be split into groups of 2. Each element in the group is then given an index, starting at 1. The matched element in each group is bth index. In this example, that would be the first element.

如果表达式为2n+1 ,则子元素将分为2组。然后,给组中的每个元素一个从1开始的索引。每个组中匹配的元素是第b个索引。 在此示例中,这将是第一个元素。

If the expression was 3n+2, the list items would be grouped into sets of 3 and the second item in each group would be matched.

如果表达式为3n+2 ,则将列表项分为3组,每组中的第二项将匹配。

If the value of b is negative, the matched element in the group is the bth index but counted backwards from index 1. In this instance, the matched element from a group will no longer match an element in that group, but in one above it.

如果值b是负的,该组中的匹配元素是bth索引但是从索引1向后计数在这种情况下,从一组匹配元件将不再匹配该组中的元素,但在一个上面。

The even keyword can be expressed as 2n. In this case, there is no value for b in the an+b expression so each ath element is matched instead; 2n would match every second element, 3n every third, 4n every fourth an so on.

even关键字可以表示为2n 。 在这种情况下, an+b表达式中没有b值,因此每个ath元素都被匹配; 2n将匹配第二个元素, 3n每三个匹配一次, 4n每四个匹配等等。

I personally find this idea of splitting child elements into groups and working out the matched index for each group very confusing – although that is how the CSS selectors spec describes it.

我个人发现将子元素分成组并为每个组计算匹配索引的想法非常混乱-尽管这是CSS选择器规范对其进行描述的方式。

I can cope with the idea of matching every nth element – every 2nd or 3rd or 4th etc. and then I like to think as the second part of the expression as an offset.

我可以应付匹配第n个元素(第2或第3或第4等)的想法,然后我想将表达式的第二部分视为偏移量。

In the case of 2n+1 I would read it as follows: “Find every second element, move the selection down by 1.”

2n+1的情况下,我将读取如下:“查找第二个元素,将选择项向下移动1”。

If the expression was 3n-5 it would read: “Find every third element and move the selection up by 5.”

如果表达式为3n-5 ,它将显示为:“查找每三个元素并将选择项上移5”。

其他:nth-child选择器 (Other :nth-child selectors)

:nth-child has a corresponding :nth-last-child pseudo class which works in the same way as :nth-child but in reverse.

:nth-child有一个对应的:nth-last-child伪类,其工作方式与:nth-child相同,但相反。

li:nth-last-child(3n) starts at the last child element and works backwards, matching every third element from the bottom of the list. This is far less common and something I don’t think I’ve ever used in a production site before.

li:nth-last-child(3n)从最后一个子元素开始,然后向后工作,与列表底部的每个第三个元素匹配。 这种情况很少见,我以前从未在生产现场使用过。

It is however, very common to select either the first or last child element. This could be done with :nth-child(1) or :nth-last-child(1) but is so common, there are :first-child and :last-child pseudo classes available as well. :first-child is the only one of this family of child selectors that works in IE8 – :last-child and any of the :nth selectors do not.

但是,选择第一个或最后一个子元素是很常见的。 可以用:nth-child(1):nth-last-child(1)但这种情况很常见,也有:first-child:last-child伪类。 :first-child是此子选择器家族中唯一可在IE8中使用的– –last :last-child ,而:nth选择器中的任何一个都不起作用。

:nth-of-type (:nth-of-type)

Something that often catches me out with :nth-child is that the selector just matches based on index of child elements and doesn’t take the type of element into account.

:nth-child通常让我感到:nth-child是,选择器仅根据子元素的索引进行匹配,而没有考虑元素的类型。

Let’s look at the following markup for a snippet of content.

让我们看一下以下标记的内容片段。

<section> 
  <h1>lorem ipsum;</h1> 
  <p>Aenean commodo ligula eget dolor. Vestibulum dapibus nunc ac augue;</p> 
  <p>Nunc sed turpis. Donec posuere vulputate arcu;</p> 
</section>

I have a section with a heading and sub-heading and a series of paragraphs beneath. I want to make the first paragraph stand out a bit by increasing the font-size to 1.5em.

我有一个带有标题和副标题的部分,以及下面的一系列段落。 我想通过将font-size增加到1.5em使第一段突出。

I might try section p:first-child, as I want to style the first paragraph in the section. But this doesn’t work as the first child of the section is actually a h1 element. In this case, I need to use the :first-of-type selector.

我可能要尝试section p:first-child ,因为我想为该部分的第一段设置样式。 但这不起作用,因为该部分的第一个子元素实际上是h1元素。 在这种情况下,我需要使用:first-of-type选择器。

There are a series of these type selectors; :first-of-type, :last-of-type, :nth-of-type and :nth-last-of-type. These behave the same way as :nth child but match the nth instances of a certain type of element.

这些类型选择器有一系列。 :first-of-type:last-of-type:nth-of-type:nth-last-of-type 。 它们的行为与:nth child相同,但是与某种元素类型的nth实例匹配。

These selectors are complex but very powerful. The browser support is IE9+ with the exception of :first-child which is IE8+. Bear this in mind when using them, but they’ve certainly gotten me out of a few difficult situations in the past.

这些选择器很复杂,但功能非常强大。 浏览器支持IE9 +,但:first-child IE8 +除外。 使用它们时请牢记这一点,但是过去它们确实使我摆脱了一些困难的情况。

奖金:快速提示 (Bonus: Quick Tip)

In this quick tip, we’ll look at when you can use nth-child and when you should use a standard class.

在此快速提示中,我们将介绍何时可以使用nth-child以及何时应使用标准类。

什么时候应该使用nth-child(When should I use nth-child?)

This is a question I get asked by students quite frequently. The first thing to note is that (unfortunately) it depends on the situation. But I’ll try and provide some good baseline criteria.

我经常问到这个问题。 首先要注意的是(不幸的)它取决于情况。 但我会尝试提供一些良好的基准条件。

Firstly, all the :nth-child like selectors are only supported in IE9 and above (with the exception of :first-child) so the first thing to check is the age of browser your project needs to support.

首先,所有类似:nth-child选择器仅在IE9及更高版本中受支持( :first-child除外),因此首先要检查的是项目需要支持的浏览器的年龄。

If you need to support IE8 (firstly, sorry to hear that!) then there’s really only one thing you can do; use classes or use :first-child.

如果您需要支持IE8(首先,很遗憾听到这个消息!),那么实际上您只能做一件事。 使用类或使用:first-child

提示1:在支持IE8时使用:first-child (Tip 1: Use :first-child when supporting IE8)

Imagine you have a horizontal unordered list of nav links and your design needs to have a border to the right of each item – but not the last item.

想象一下,您有一个水平无序的导航链接列表,并且您的设计需要在每个项目的右侧(而不是最后一个项目)的右侧都有一个边框。

Instead of adding the border on the right and needing to remove it from the last one, add the border on the left and remove it from the first one.

无需在右侧添加边框并需要从最后一个边框中删除它,而是在左侧添加边框并从第一个边框中删除它。

.site-nav li {
  border-left: 2px solid grey;
}
.site-nav li:first-child {
  border: 0;
}

You can use a similar trick for borders on top/bottom too.

您也可以对顶部/底部的边框使用类似的技巧。

If you’re lucky enough to not need support for IE8, read on…

如果您很幸运不需要支持IE8,请继续阅读...

提示2:使用:first-child:last-child代替类 (Tip 2: Use :first-child and :last-child instead of classes)

If you’re building or using a grid system and need to do something special for your first and last columns in a row, I’d favour using the :first-child and :last-child pseudo classes over adding classes like .first or .last direct in the HTML.

如果您正在构建或使用网格系统,并且需要对一行的第一列和最后一列做一些特殊的事情,我宁愿使用:first-child:last-child伪类,而不是添加诸如.first.last直接在HTML中。

This will keep your HTML neater and means that you don’t have to think too much when crafting your layout. Layout can be sometimes difficult, so the less thinking you have to do about it the better.

这将使HTML保持整洁,这意味着您在设计布局时不必考虑太多。 布局有时可能会很困难,因此,您不必花太多时间思考它就更好了。

提示3:使用:nth-child替代样式 (Tip 3: Use :nth-child for alternating styles)

A classic example of alternating styles would be having different colored backgrounds for even or odd rows in a table. Another could be floating even or odd blocks of content to the left and right side of a page or container – perhaps for a comment thread or message conversation.

交替样式的经典示例是表格中偶数或奇数行具有不同的彩色背景。 另一个可能是将内容的偶数或奇数块浮动到页面或容器的左侧和右侧–可能是用于注释线程或消息对话。

For these kind of situations, I use :nth-child(odd) and :nth-child(even). To keep your code lean, you should just write the first state without any nth-child and then use the higher specificity of using nth-child to set up the alternate style.

对于这种情况,我使用:nth-child(odd):nth-child(even) 。 为了使代码保持精简,您应该只编写第一个状态而没有任何nth-child ,然后使用使用nth-child的更高的特殊性来设置替代样式。

/* do this */
.data-table tr {
  background: white;
}
.data-table tr:nth-child(even) {
  background: lightgrey;
}

/* not this */
.data-table tr:nth-child(odd) {
  background: white;
}
.data-table tr:nth-child(even) {
  background: lightgrey;
}

提示4:避免使用怪异而复杂的nth-child表达式 (Tip 4: Avoid weird and complex nth-child expressions)

For other, more complex selections of the page, I’d favor using classes directly in the HTML over confusing nth-child expressions.

对于页面的其他更复杂的选择,我希望直接在HTML中使用类,而不要使nth-child表达式令人困惑。

li:nth-child(-n+3) or li:nth-child(5n+1):not(nth-child(3n-1)) are just a bit too crazy and take a lot of brain power to decipher what they actually means (Hint: I have no idea – I just made the last one up, although technically it could work!)

li:nth-child(-n+3)li:nth-child(5n+1):not(nth-child(3n-1))有点太疯狂了,需要很多脑力才能破译它们实际上意味着(提示:我不知道–我只是做了最后一个,尽管从技术上讲它可以工作!)

Unfortunately, some designs are so complex that often an approach like this feels necessary but imagine coming back to this kind of code months later and trying to work out what you were trying to do – it could take a while even for the most competent of CSS experts!

不幸的是,有些设计是如此复杂,以至于常常需要一种这样的方法,但是想像几个月后再回到这种代码,并尝试弄清您想做的事情-即使对于最有能力CSS来说,也可能需要一段时间。专家!

提示5:无法控制HTML时,请使用nth-child (Tip 5: Use nth-child when you can’t control the HTML)

This may sound like an odd statement. Surely, as the developer or designer one of our most important jobs is to control the HTML.

这听起来像是一个奇怪的陈述。 当然,作为开发人员或设计师,我们最重要的工作之一就是控制HTML。

The situation I’m talking about here is when you’re dealing with a content management system.

我在这里谈论的情况是在处理内容管理系统时。

When building templates for a CMS based website, you’ll likely be able to control the HTML structure and add your classes and data attributes as and when needed. But sometimes your template will have a place where it spits out a whole load of content from a text field or text area from within the CMS. A classic example is WordPress’ the_content which is one big chunk of HTML which you may have little or no control over.

在为基于CMS的网站构建模板时,您将可能能够控制HTML结构并在需要时添加类和数据属性。 但是有时您的模板会有一个地方,它会从CMS内的文本字段或文本区域吐出全部内容。 一个经典的例子是WordPress的the_content ,它是HTML的一大块,您可能几乎无法控制。

In these cases, the :first-child, :last-child and :nth-child selectors can get you out of a tight corner.

在这些情况下, :first-child:last-child:nth-child选择器可以使您摆脱困境。

So, there you have it. 5 tips for using (or not using) one of the most powerful and flexible CSS selectors there is.

所以你有它。 使用(或不使用)最强大,最灵活CSS选择器之一的5个技巧。

翻译自: https://www.sitepoint.com/atoz-css-screencast-nth-child/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值