英文:
nth-child selects everything
问题
我试图理解:nth-child是如何工作的,但不理解为什么它选择了下面的所有内容:
:nth-child(2) {
color: blue;
}
同样的情况也发生在我使用nth-child(1)
时,但当我使用nth-child(3)
时,它只选择了"two"和"hello"。
:nth-child(3) {
color: blue;
}
可以有人为我详细解释一下它是如何工作的,以便我能理解这个概念吗?
英文:
I'm trying to understand how the :nth-child works but don't understand why it is selecting everything below:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
:nth-child(2) {
color: blue;
}
<!-- language: lang-html -->
<div>
hello
<h1>test</h1>
<p>one</p>
<p>two</p>
<p>three</p>
<p>four</p>
</div>
<div>
<span>hey</span>
</div>
<p>hello</p>
test
<!-- end snippet -->
Same happens when I do nth-child(1)
but then nth-child(3)
selects only "two" and "hello"
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
:nth-child(3) {
color: blue;
}
<!-- language: lang-html -->
<div>
hello
<h1>test</h1>
<p>one</p>
<p>two</p>
<p>three</p>
<p>four</p>
</div>
<div>
<span>hey</span>
</div>
<p>hello</p>
test
<!-- end snippet -->
Can somebody give me a walkthrough on how it's working so I can understand the concept?
答案1
得分: 2
你忘了一些东西。nth-child 是一个选择器,用于选择你同一列表中的特定项。看看HTML,h1元素是其父元素div元素的第二个子元素,因此被选中,并且其颜色设置为蓝色。其他p元素也是其父元素div元素的第二个子元素,因此它们也被选中,其颜色设置为蓝色。
所以,如果你想要给**"hey"**上色,你需要升级代码为,
div:nth-child(2) {color: blue;}
如果你想要给**"two"**上色,你需要升级代码为,
p:nth-child(2) {color: blue;}
你没有做错任何事,只是忘了在HTML中选择元素。
希望这对你有所帮助。
英文:
you forgot something. nth-child is a selector is selecting one specific item in your same list.look HTML, the h1 element is the second child of its parent div element, so it is selected and its color is set to blue. The other p elements are also the second child of their parent div element, so they are also selected and their color is set to blue.
so if you need color the "hey" , you need to upgrade the code to ,
div:nth-child(2) {color :blue;}
you need color the "two", you need to upgrade the code to,
p:nth-child(2) {color :blue;}
you not done anything wrong. only you forgot select element in html.
I hope this help you.
答案2
得分: 1
你可以检查一个元素以查找它从哪里获取其样式。在Firefox中,右键单击一个元素,然后单击Inspect以打开开发者工具(Chrome有一个非常类似的过程):
我们在这里看到<h1>
从<body>
继承了颜色属性,这是因为它是<html>
的第二个子元素。同样,使用:nth-child(1)
,将匹配<html>
,并且所有元素都将继承自那里的颜色。最好只在具体的父元素/祖先上使用:nth-child()
,这样您就不会出现意外的继承关系。
英文:
You can inspect an element to find out where it's getting its styles from. In Firefox, right-click an element and click Inspect to bring up the Developer Tools (there is a very similar procedure for Chrome):
We see here that <h1>
is inheriting the color property from the <body>
, which is selected because it's the 2nd child of <html>
. Likewise, with :nth-child(1)
, <html>
is matched and everything will inherit color from that. It's smart to use :nth-child()
only with a combinator targeting a specific parent/ancestor so you don't have unexpected inheritances like that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论