What is the proper CSS selector to select the first div within a class or with a specific id? This seems to be much easier with parent/child elements but I haven't found anything for simple elements.
Update: solution
The cleanest, most compatible solution I found was .class ~ .class which selects all the latter classes that follow the former class. For example, if you wanted to remove the top border from the first element within its class you would:
<style>
.dolphin {
border-top:0;
}
.dolphin ~ .dolphin {
border-top:1px solid #000;
}
</style>
Or you can select by ID: #elementID. div[id="elementID"]
The ID selector #first has priority over the class and tag selectors.
The CSS id Selector The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
The basic rule that you need to keep in mind while using classes and ids in CSS is that, id is used for single elements that appear on the page for only once (e.g. header, footer, menu), whereas class is used for single or multiple elements that appear on the page for once or more than once (e.g. paragraphs, links, ...
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 :) )
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 :
and here is a demo of my answer :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With