简体   繁体   中英

css selector for first child element

Let's say my html looks like this:

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

I want to get the first direct child of .container .

I could do .container > div:first-child but that's assuming the it is a div which is not always the case.

Use the :first-child pseudo-class without a tagname:

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

Not using the element itself, but a class is a better solution and way more . ,不使用元素本身,而是使用类是一种更好的解决方案,并且使用更多

And give the class to the children of the element, not only the container like this:

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:

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

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

You can see it in action here: http://jsfiddle.net/Roobyx/ygP4B/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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