I have this CSS selector:
.img + *{
}
Which, from my understanding, will make the browser look for all the elements and then select only those which follow an element with the class img
. Is there a better way of writing this selection to improve performance?
Relevant HTML structure:
<div class="media">
<div class="img">
<img src="an-image.jpg">
</div>
<random-element>content is here</random-element>
</div>
2 Answers 2
My recommendation would be to not worry about the performance (see: http://www.kendoui.com/blogs/teamblog/posts/12-09-28/css_tip_star_selector_not_that_bad.aspx for actual tests).
If you're still not convinced that it's not as bad as everyone makes it out to be, then your only real option is to modify the contents of <random-element />
.
<div class="media">
<div class="img">
<img src="an-image.jpg">
</div>
<random-element><div id="foo">content is here</div></random-element>
</div>
Which allows your CSS to be:
.img + #foo { ... }
Or just
#foo { ... }
Here is something that you could do in your HTML, you could get rid of the <div class="img>
this looks like it would be extra code for you to write, anything that you can style on a div
you should be able to style on the <img>
tag as well, you can also give your image tag an attribute of class="img"
if you know that you want to change the style on every <img>
tag on the document, you could do your CSS like this,
img
{
/* Style */
}
this will change the style for all image tags in the document, and later if you want a one image to be different then you would give that specific image tag a class of whatever
and do this (after the previous img
styling)
img.whatever
{
/* different Style */
}
this will override only the styles that you specify, for this specific image tag
-
3\$\begingroup\$ There are plenty of styles that cannot be applied to img elements: before/after pseudo elements,
display: table
, etc. The styles are meant to apply to the element that follows the.img
element, and modifying the markup is out of the question anyway. \$\endgroup\$cimmanon– cimmanon2013年11月26日 22:00:18 +00:00Commented Nov 26, 2013 at 22:00 -
\$\begingroup\$ @cimmanon, good point. \$\endgroup\$Malachi– Malachi2013年11月26日 23:55:08 +00:00Commented Nov 26, 2013 at 23:55
img
" is incorrect. It selects only elements which follow an element with the classimg
. Your HTML excerpt, however, suggests that you correctly expect that your CSS selector selects<random-element>
. w3.org/TR/CSS2/selector.html#adjacent-selectors \$\endgroup\$<random-element/>
to be a placeholder to show where the content that can be modified starts and ends. In the templating library I use, custom tags like this are used as hooks for placing dynamic content and do not actually appear in the rendered document's source. While you are technically correct, it may not apply in this particular instance. \$\endgroup\$