CSS selector: first div inside id or class

What is the correct CSS selector to select the first div inside the class or with a specific id? This seems a lot 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 last classes that follow the previous class. For example, if you want to remove the top border from the first element inside your class, you should:

<style> .dolphin { border-top:0; } .dolphin ~ .dolphin { border-top:1px solid #000; } </style> 
+6
source share
5 answers

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

 .class div:first-child 

This, however, will not work if you have the following HTML:

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

This will not work because the div not the first child element of .class . If you don’t target div , then I would suggest adding another container (or adding a class to this div , which you like :))

+21
source

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

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

same if you want to select inside id just do it

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

but if you have an identifier, yours should have ONLY , otherwise you would encode Invalid HTML, just use a simple selector like this for id

 #yourID{ // Your Properties } 

also note that in @sourcecode answer that it currently does not have> in its example, without this, it will not select the first div inside the class, but will most likely select every first div inside this class to check this script for example of this

Demo selector from each group

and here is a demonstration of my answer

First Demo Only

+5
source

you can use

.class div:first-child{ your css }

+1
source

Just use id - it should be unique to the page, and so you know exactly which element you are executing

+1
source

You can use the following pseudo classes:

  • : first-baby
  • : fifth child (1)

Or you can select by ID:

  • #elementID
  • DIV [ID = "elementID"]

The difference between the two above is specific; using "#elementID" will have higher specificity (priority) than using the attribute selector "div [id =" elementID "], but both are the right way to select an element.

0
source

Source: https://habr.com/ru/post/946881/


All Articles