Sunday, May 27, 2018

css - Selected the first instance of a class without knowing position under parent





I'm trying to always select the first element with the class ".chartKeyListItem". It is under the parent "chartKey". So this works great with the first-child selector if it is the first element but sometimes I have 3 items before it so I'd have to use the nth-selector(4) this works for that instance. But my code should be able to handle both without breaking eachother. (Which it does if both CSS classes are loaded in because for the first instance it targets the 1st and 4th "chartKeyListItem") Is there a way to just only select the first ".chartKeyListItem"?



Also, the amount of chartKeyListItem divs is not definite and can be anywhere from 2 to 20 and the MinMax labels will only show up for some pages but the CSS needs to be able to handle when they're are there and when they are not...



Code below:
Instance 1:




"
//Just want to add margin to this one


//THIS ONE GETS BOTH CLASSES WHICH I DONT WANT



Instance 2:




"
Min

Max


//Just want to add margin to this one



//This one will get both class too




CSS:



.chartKeyListItem:first-child{
margin-left: 60px !important;
}
.chartKeyListItem:nth-child(4) {
margin-left: 60px !important;

}

Answer



For this, you would need some sort of first-of-class selector which sadly we don't have yet. However, you can achieve the same effect :)



.chartKeyListItem {
margin-left: 60px !important;
}

.chartKeyListItem ~ .chartKeyListItem {

margin-left: 0 !important;
}


How it works: you are styling the class, and then any instances of that class that are preceded by that class are over written with 0 margin-left. You can find out just how ~ works here.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...