Css3 selector question for all but first select
To neatly target all <select>
elements except the first, use:
This nifty selector skips over the first <select>
under any given parent, applying your styles only to the rest. When directly paired sibling <select>
s are huddled under the same parent:
Here, your style is applied to all <select>
s that follow the first, within the same parent.
Leave the first one out
In the everyday hustle and bustle of styling sequences, you might, intentionally or not, need to keep the 'first select' out of your styling festivities. The pseudo-classes :not()
and :first-child
lend a helping hand when striking out the first one:
This arsenal of selectors narrows down all selects to only those who are united under any div_. The direct children, that is – as indicated by the child combinator >
.
The nth-child maneuver
At times, though, you might need to pile up a couple more pseudo-classes for a higher level of control. Here, the :nth-child()
and :nth-of-type()
pseudo-classes make their entry:
This string of command targets and styles only select descendants of the second, third, fourth – and so on – div child in .options
.
Following the leader
When you gotta apply some styles to all the <select>
s that follow the first – like a line of faithful minions - go with:
The ~
combinator, also known as the 'subsequent sibling' selector, targets the <select>
elements that are direct siblings of the div and beyond.
Playing compatible
While the above selectors neatly fall in line with the CSS3 specifications, make sure to give them a compatibility check with certain peculiar browsers that might throw a wrench in your works.
A complexity of specificity
When layering your page with styles, remember that the specificity of CSS selectors can make or break your output. Over-stacking pseudo-classes? Might lead to an override of other styles you diligently put in place. So walk this tightrope of matching specificity with caution, and sprinkle !important
only where crucial.
Jig-sawing with selectors
Play around a bit, these CSS selectors fit into different scenarios:
- Descendent specificity:
body:not(.home) .content select
– keeps the selects on.home
feeling warm and cozy, i.e., without your styles. - State-based styling:
select:not(:disabled)
– styles come knocking only when the select is up and jumping. - Custom attributes:
[data-custom]:not([data-ignore])
– if there is adata-custom
attribute but nodata-ignore
, it's styling time!
Some stitches in time...
So while :not()
can be your CSS savior, it can also get tangled into an overly complex selector monster. That's a nightmare no amount of regular testing will conquer. However, regular tests against different HTML structures? Now, that's your regular knight-in-shining-armor.
Was this article helpful?