Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the first child without knowing the type of the 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 without declaring what type the HTML element is.

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

.foo span:first-child

I want CSS that will work on the first element even if the developer will choose to make changes inside that div.

Is there any way to do it?

like image 465
mashiah Avatar asked Apr 28 '15 12:04

mashiah


2 Answers

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

.foo > :first-child {
    /* styling here */
}
like image 86
putvande Avatar answered Sep 29 '22 08:09

putvande


.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> 
like image 44
Puneet Avatar answered Sep 29 '22 10:09

Puneet