Friday, 5 May 2017

css selectors - Targeting the first class instance on a page with CSS




I have a bunch of divs with the class of showreel and I'd like the first one to have a higher margin value. I'm trying to achieve this using CSS advanced selectors but can't seem to figure it out.



I know that you can target native elements like
p:first-child
but can I use it for div classes e.g.
.showreel:first



Looked around quite a bit but I just find information on native elements. Any help appreciated, but would rather have a CSS solution vs. a JS solution.



Thanks



Answer



No such functionality exists in CSS. You will need to use a JS solution to find them on the client machine, or a server-side solution to apply an additional class to the first element with this CSS class. Which to use depends on how important it is to style this item uniquely.



Using jQuery, you could find the first instance of the class via:



var firstAsJQueryObject = $('.showreel').eq(0);
var firstAsDOMElement = $('.showreel')[0];


Using pure JavaScript on modern browsers:




var firstAsDOMElement = document.querySelector('.showReel');


Using pure JavaScript on older browsers:



function findFirstElementWithClass(className){
var hasClass = new RegExp("(?:^|\\s)"+className+"(?:\\s|$)");
for (var all=document.getElementsByTagName('*'),len=all.length,i=0;i if (hasClass.test(all[i].className)) return all[i];

}
}
var firstAsDOMElement = findFirstElementWithClass('showReel');


If you are going to use JavaScript, instead of applying the visual style through JavaScript I would suggest apply a class using JavaScript and still using CSS to style the element:



// Using jQuery for simplicity
$('.showreel').eq(0).addClass('first-showreel');



.first-showreel {
/* apply your presentation here */
}





Edit: Note that the much-higher-voted answer by @mickey_roy is incorrect. It will only work when the element with the class you want is also the first element of its type on the page.




Writing .showreel:nth-of-type(1) means, "Find me the first element with each class name that also has the showreel class applied." If the same element type appears earlier on the page without the class, it will fail. If a different element type shares the same class, it will fail.



The question asks how to select the first instance of the class. See below for an example of how very wrong that answer is for this question.





div { color:red }
.showreel:nth-of-type(1) {
font-weight:bold;
color:green

}

not this

this should be green

not this

not this

not this


not this





No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...