简体   繁体   English

第一个子元素的CSS选择器

[英]css selector for first child element

Let's say my html looks like this: 假设我的html看起来像这样:

<div class="container">
    <... some html here ...>
</div>

I want to get the first direct child of .container . 我想成为.container的第一个直接孩子。

I could do .container > div:first-child but that's assuming the it is a div which is not always the case. 我可以做.container > div:first-child但这是假设它是一个div ,但并非总是如此。

Use the :first-child pseudo-class without a tagname: 使用不带标记名的:first-child伪类:

.container > :first-child

This will grab any element that is the immediate first child, regardless of its tagname. 无论其标记名是什么,它都将获取任何作为直接第一个子元素的元素。 This is similar to the way in which we use other pseudo-classes such as :hover which alone targets any element, while a:hover targets only the hover state of anchors. 这类似于我们使用其他伪类的方式,例如:hover仅针对任何元素,而a:hover仅针对锚点的悬浮状态。

Not using the element itself, but a class is a better solution and way more semantic for so many reasons . 出于多种原因 ,不使用元素本身,而是使用类是一种更好的解决方案,并且使用更多语义

And give the class to the children of the element, not only the container like this: 并将类提供给元素的子元素,而不仅仅是这样的容器:

HTML: HTML:

<article class="container">
  <p class="blah">First paragraph...</p>
  <p class="blah">Lorem ipsum...</p>
  <p class="blah">Dolor sit amet...</p>
</article>

CSS: CSS:

.blah {
    background: red;
    color: white;
}

.blah:first-child {
    background: #000;
}

You can see it in action here: http://jsfiddle.net/Roobyx/ygP4B/ 您可以在此处查看其运行情况: http : //jsfiddle.net/Roobyx/ygP4B/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM