0

I have the same class several times in the same DOM (as normal), and I'd like to apply a padding to the first element in the DOM using that class. ( I am using sass).

So far I tried>

.myclass{
    &:first-of-type{
        padding-top: 50px;
    }
}

and

.myclass{
    &:nth-child(1){
        padding-top: 50px;
    }
}

and

.myclass{
        &:nth-of-type(1){
            padding-top: 50px;
        }
    }

and only the last piece of code seems to have any effect on the DOM adding padding to ALL elements using .myclass (and not only the first one).

Any idea about what I doing wrong?

carlosbvz
  • 163
  • 2
  • 14
  • It can't be done with CSS ... – vals Mar 30 '16 at 19:48
  • It can super be done with CSS – teefars Oct 30 '21 at 10:04
  • I went to answer but apparaently someone marked as duplicate (which also didn't have a proper answer). There are 2 ways of acomplishing this: you can add the first child thingy and then undo the padding for all the next elements with the [~ selector](https://www.w3schools.com/cssref/sel_gen_sibling.asp). like `.myclass:first-of-type ~ .myclass` – teefars Oct 30 '21 at 10:07
  • Another way is to just add a crazy function to the selector matching number, like `.myclass:nth-child(1+ 900n)`. – teefars Oct 30 '21 at 10:08
  • It is not a duplicate because here he states it is in the same DOM (all siblings) and the answer marked is for all DOM (not the same parent element) – teefars Oct 30 '21 at 10:13

1 Answers1

2

How about :first-of-type ?

.myclass:first-of-type {
  // do something
}

See this fiddle

EDIT

See @Ryan Dantzler fiddle about this solution using SASS :

https://jsfiddle.net/swpk5x86/2/

Vincent G
  • 8,547
  • 1
  • 18
  • 36