... ---> can be the...">

Choosing the first child without knowing the type of first child

I have the following HTML code:

<div class="foo">
   ...
   <span> ---> can be the first
   <h1> ---> can be the first
   <h2> ---> can be the first
   and so on...
   ...
</div> 

I want to add some CSS styles to the first element, but not declaring which type the HTML element is.

For example, this piece of code will NOT help me:

.foo span:first-child

I want CSS to work on the first element, even if the developer wants to make changes inside this div.

Is there any way to do this?

+4
source share
5 answers

You can simply add this CSS, which will target any element that is the first child .foo.:

.foo > :first-child {
    /* styling here */
}
+4
source

.foo > *:first-child
{
  color:green;
}
<div class="foo">
   ...
  <h2> ---> can be the first another</h2>
   <span> ---> can be the first</span>
  
   <h1> ---> can be the first</h1>
   
   and so on...
   ...
</div> 
Run codeHide result
+1
source
.foo>*:first-child {
    /*style here*/
}
+1

:

.foo > :first-child {
    /* Your Styles */
}

.foo > :first-of-type {
    /* Your Styles */
}

.foo > :nth-child(1) {
   /* Your Styles */
}
+1

CSS 2.1 :

- , , pseudo-classes, . [...]

, . : , " > " "+".

. CSS3 .

, . , , :

The universal selector written with "*" matches the name of any element type. It matches any element of the tree.

However, in this case, the universal selector is not alone; there is also a pseudo-class :first-child. So you can omit *:

If the universal selector is not the only component of a simple selector , the "*" may be omitted.

So a simple selector will be one of them (they are equivalent):

:first-child
*:first-child

And the full selector will be

.foo :first-child
.foo *:first-child
0
source

All Articles