请有人通过简要解释css中父元素或子元素的含义来指导我。我已经阅读了很多关于css选择器的教程,其中总是提到这些术语,例如first-child元素,父元素,同一个父母e.t.c的孩子 请在一组html元素中,其中哪些是父母或孩子。 如果兄弟,叔叔,侄子或元素的表弟也存在请将它们包括在你的答案中,谢谢你们所有提前
答案 0 :(得分:3)
我发现很难相信任何人都不清楚这一点,但现在就去了。
祖先是父母或祖父母(或曾祖父母等)的元素。这意味着它们在HTML结构中更高。与家人比较。你的父亲是你的父母,他的父亲是他的父母和你的父母,依此类推。你是你父亲的孩子。
<div id="parent">
<div id="child"></div>
</div>
在考虑一组子项的第一个元素时,称为first-child
,可以使用CSS3进行选择。例如,在这个HTML中:
<ul id="parent">
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
</ul>
结合这个CSS:
li:first-child {color: red;}
第一个列表项“First list item”将为红色,但其他列表项不会。所有li
都是同一父项的子项(或“子元素”),即ID为“parent”的ul
。列表项目是彼此的“兄弟姐妹”,如果愿意,他们是兄弟姐妹。
使用相同的逻辑,:last-child
选择集合中的最后一个子节点。所以用这个CSS
li:last-child {color: blue;}
列表中的最后一项,即“第三列表项”,将为蓝色。您可以在here中看到:first-child
和:last-child
。
在某些情况下,您可能需要使用:first-of-type
而不是:first-child
!你看,第一个孩子选择第一个孩子,无论它是什么类型,而第一个孩子,顾名思义,选择该类型的第一个元素。
以下HTML解释了它。
<div id="parent">
<span class="child">I am the first child and also the first of type "span"!</span>
<span class="child">I am neither the first child, but second, nor first of type "span" :(</span>
<span class="child">I am neither the first child, but third, nor first of type "span" :(</span>
<blockquote class="child">I might not be the first child, but fourth, but I am the first of my type "blockquote!" Funny enough, I am also the last of my type!</blockquote>
<span class="child">And I am just sitting here, being the last-child and the last of my type "span"</span>
</div>
在此Fiddle中查看此操作!
答案 1 :(得分:0)
父/子面额是指html结构。元素可以相互嵌套。在下面的示例中,两个div位于第一个div中。他们都是包含div的孩子。包含div是孩子的父母。
<div id="1">
<div id="2"></div>
<div id="3"></div>
</div>