{"id":1203,"date":"2014-06-30T14:30:53","date_gmt":"2014-07-01T00:30:53","guid":{"rendered":"http:\/\/mymonkeydo.com\/?p=1203"},"modified":"2014-06-30T14:30:53","modified_gmt":"2014-07-01T00:30:53","slug":"pseudo-selector-first-child-of-class","status":"publish","type":"post","link":"https:\/\/mymonkeydo.com\/pseudo-selector-first-child-of-class\/","title":{"rendered":"Pseudo Selector First Child of Class"},"content":{"rendered":"
How do you apply a style to only the first element with a certain class?<\/p>\n
\n\n.just-this-one {\n\nbackground:blue;\n\n}\n\n<\/pre>\n\n\n<div class="top">\n\n<div class="not-this-one">not this one<\/div>\n<div class="just-this-one">just this one<\/div>\n<div class="just-this-one">but not really<\/div>\n\n<\/div>\n\n<\/pre>\n:first-child does not do this, that just selects the very first child no matter what the class is.<\/p>\n
:first-of-type doesn’t even do this. \u00a0but you would think it does, but “type” here\u00a0implies the HTML element type like “div”, “p”, etc.<\/p>\n
<\/p>\n
Solution<\/h2>\n
Use the tilde “~” to “undo” styles on elements where the class previously appeared. \u00a0So first apply the style you want to all .just-this-one elements. \u00a0Then apply “undo” that style for all\u00a0subsequent elements.<\/p>\n
\n\n.just-this-one {\n\nbackground:blue;\n\n}\n\n.just-this-one ~ .just-this-one {\n\nbackground:none;\n\n}\n\n<\/pre>\nThis\u00a0genius solution found on stack overflow (not the accepted answer):<\/p>\n