How to add css property to first div with specific class name?

I am trying to add a bottom margin to the first <div> using the "unit" class.

 <div id="wrapper-related-albums"> <div class="header">...</div> <div class="unit">...</div> //add margin-bottom to this one!!!! <div class="header">...</div> <div class="unit">...</div> </div> #wrapper-related-albums .unit:first-child {margin-bottom:20px;} // doesn't work!!! #wrapper-related-albums .unit:first-of-type {margin-bottom:20px;} // doesn't work!!! 
+4
source share
2 answers

There are several options depending on your markup:

Second child with class unit:

 #wrapper-related-albums .unit:nth-of-type(2) { } #wrapper-related-albums .unit:nth-child(2) { } 

Adjacent brother (with class unit) of the first element:

 #wrapper-related-albums :first-child + .unit { } 

I do not believe that you can simply select the "first .unit ", but you can add margin to all but the last, if it always falls last:

 #wrapper-related-albums .unit { margin-bottom: 20px; } /* negate the above rule */ #wrapper-related-albums .unit:last-child { margin-bottom: 0px; } 
+2
source

More general / flexible solution

Wesley's answer is well suited for your specific html markup, as it assumes that .unit will become the second item on the list. So in your case, this may be so, and its solution works well. However, if someone is looking for a more general solution, then the following should be done:

 #wrapper-related-albums .unit { /* code for the first one */ margin-bottom: 20px; } #wrapper-related-albums .unit ~ .unit { /* code for all the following ones */ margin-bottom: 0px; } 

Using a common selector ( ~ ) like this will override all but the first .unit , which allows you to use the first .unit anywhere in the wrapper (not only at position # 2, but at the position you don't need to be known in advance). Here's a script illustrating this with a color change.

+4
source

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


All Articles