CSS selector: first div within an id or class

To select the first div in a class I would recommend using this method :

.yourClassName > div:first-child{
   // Your properties
}

Same if you want to select within an id, just do this :

#yourUniqueId > div:first-child{
   // Your properties
}

But if you do have an id, your should ONLY have one anyway. Otherwise you would be coding Invalid HTML. Just use a simple selector like this for id's :

#yourID{
    // Your Properties
}

Also note, that in @sourcecode's answer, he doesn't currently have the > in his example. Without this it will not select the first div within a class but will rather select every first div within that class. Check this fiddle out for an example of that :

Demo First Selector from each group

and here is a demo of my answer :

Demo First Selector ONLY


If you want to select the first div within a specific class then you can use:

.class div:first-child

This however won't work when you've got the following HTML:

<div class="class">
    <h1>The title</h1>
    <div>The CSS won't affect this DIV</div>
</div>

It won't work because the div isn't the first child of the .class. If you wan't to target that div in this case I'd suggest adding another container (or adding a class to that div whatever you like :) )


you can use

.class div:first-child{ your css }

Tags:

Css