This question already has answers here:
Understanding CSS selector priority / specificity
(4 answers)
Closed 4 years ago.
This must be a very simple question for HTML ninjas out there, but I feel I'm missing something obvious here. Here is a snippet:
#red span {
color: red;
}
#green span {
color: green;
}
<div id="red">
<p><span>red</span></p>
<div id="green">
<p><span>green</span></p>
</div>
</div>
If I swap the stylesheet order, all of the text becomes red:
#green span {
color: green;
}
#red span {
color: red;
}
<div id="red">
<p><span>red</span></p>
<div id="green">
<p><span>green</span></p>
</div>
</div>
This happens despite the fact that <div id="green"> is a more inner parent of <span>green</span> than <div id="red"> in the DOM tree. I suppose it doesn't take precedence simple because its CSS now appears first in the order of stylesheets. So the order of stylesheets is what matters here.
Is this an expected behavior? Is this implementation/browser specific? Is there some official specs detailing that?
Finally, is there any CSS selector syntax I can use to make it work as in the first snippet, without relying on the order of stylesheets or adding new class names, ids, etc?
Yes, the result you got is absolutely expected—well, maybe not expected, but they are correct. Here are the official specs. And here’s a tweet poll of mine detailing the exact same problem. (Spoiler: the majority of voters got it wrong.) Read the replies for a more in-depth discussion.
Currently, there’s not any CSS technology that takes “closest parent” scope into account. And this is a common misconception a lot of programmers have. (CSS is not a programming language.) A typical programmer will think, “The selector #red span means wherever I see a #red, look for a span inside, and then apply the styles. Since #green span is inside the #red, the green will apply after the red.” This is simply incorrect.
The way CSS actually applies styles is that it looks at each element, then goes through the stylesheets from top to bottom, decides if it matches, and then applies/overrides styles as it goes. That’s just one aspect of the cascade, among others (such as inheritance and specificity). Since in your second example #red span comes last in the CSS source, it gets applied last, overriding #green span, regardless of “how close” the span is within the #red in the DOM.
To fix your specific problem, the easiest thing to do is use a direct child selector, like #red > p > span and #green > p > span. But as you’d suspect, these selectors would have to be updated if you ever change the HTML. Coupling your CSS and HTML is a hassle, especially as your project grows.
The best strategy is not to depend on the DOM to style your elements. What happens when you move the span outside the #red? Would you want it to keep its style? For maintainable and scalable CSS, you should use classes only (not IDs) and apply the class to the actual element you want styled, without depending on DOM structure or parent-child relationships. That way, when your HTML structure changes, you don’t have to adjust your CSS to match.
Example:
.red {
color: red;
}
.green {
color: green;
}
<div>
<p><span class="red">red</span></p>
<div>
<p><span class="green">green</span></p>
</div>
</div>
You can use > selector to make it apply to only specific span inside the div with the id you give and not all the span inside the div
#green > span {
color: green;
}
span {
color: red;
}
<div id="red">
<p><span>red</span></p>
<div id="green">
<span>green</span>
</div>
</div>
If you want to do it to all descendants, you can achieve it by Javascript like following, it decreases many line of codes if you want to apply many colors, but will be slower time than css. It's up to your preferences
var colors = ['red', 'green', 'blue', 'orange', 'brown']
var spans = document.querySelectorAll('span');
spans.forEach(function(spanElement) {
colors.forEach(function(color){
if(spanElement.closest(`#${color}`)){
spanElement.style.color=color
}
})
})
<div id="red">
<span>red</span>
<div id="green">
<span>green</span>
<p><span>green</span></p>
</div>
<div id="blue">
<span>blue</span>
</div>
<div id="orange">
<span>orange</span>
</div>
<div id="brown">
<span>brown</span>
</div>
</div>
Related
Is it possible to use the CSS3 selector :first-of-type to select the first element with a given class name? I haven't been successful with my test so I'm thinking it's not?
The Code (http://jsfiddle.net/YWY4L/):
p:first-of-type {color:blue}
p.myclass1:first-of-type {color:red}
.myclass2:first-of-type {color:green}
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
No, it's not possible using just one selector. The :first-of-type pseudo-class selects the first element of its type (div, p, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.
Unfortunately, CSS doesn't provide a :first-of-class selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:
.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
Explanations and illustrations for the workaround are given here and here.
The draft CSS Selectors Level 4 proposes to add an of <other-selector> grammar within the :nth-child selector. This would allow you to pick out the nth child matching a given other selector:
:nth-child(1 of p.myclass)
Previous drafts used a new pseudo-class, :nth-match(), so you may see that syntax in some discussions of the feature:
:nth-match(1 of p.myclass)
This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.
This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.
However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :
:not(.myclass1) + .myclass1
Full working code example:
p:first-of-type {color:blue}
p:not(.myclass1) + .myclass1 { color: red }
p:not(.myclass2) + .myclass2 { color: green }
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
I found a solution for your reference. from some group divs select from group of two same class divs the first one
p[class*="myclass"]:not(:last-of-type) {color:red}
p[class*="myclass"]:last-of-type {color:green}
BTW, I don't know why :last-of-type works, but :first-of-type does not work.
My experiments on jsfiddle... https://jsfiddle.net/aspanoz/m1sg4496/
This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.
p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }
The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
You can do this by selecting every element of the class that is the sibling of the same class and inverting it, which will select pretty much every element on the page, so then you have to select by the class again.
eg:
<style>
:not(.bar ~ .bar).bar {
color: red;
}
<div>
<div class="foo"></div>
<div class="bar"></div> <!-- Only this will be selected -->
<div class="foo"></div>
<div class="bar"></div>
<div class="foo"></div>
<div class="bar"></div>
</div>
As a fallback solution, you could wrap your classes in a parent element like this:
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<div>
<!-- first-child / first-of-type starts from here -->
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
</div>
Not sure how to explain this but I ran into something similar today.
Not being able to set .user:first-of-type{} while .user:last-of-type{} worked fine.
This was fixed after I wrapped them inside a div without any class or styling:
https://codepen.io/adrianTNT/pen/WgEpbE
<style>
.user{
display:block;
background-color:#FFCC00;
}
.user:first-of-type{
background-color:#FF0000;
}
</style>
<p>Not working while this P additional tag exists</p>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
<p>Working while inside a div:</p>
<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>
I found something that works
If you have a bigger class which contains something like grid, all of elements of your another class
You can do like that
div.col-md-4:nth-child(1).myclass{
border: 1px solid #000;
}
Simply :first works for me, why isn't this mentioned yet?
HTML
<div class='container'>
<p>foo</p>
</div>
CSS
.container {
color: red;
}
p {
color: blue
}
Code Pen
The applied color is blue. Why is this? I was thinking that since .container has more specificity than p, the color would end up being red.
What is happening here? Why is it blue?
My hypothesis is that the process is "Does p have any selectors? If so use it and don't look up for .container. If it didn't have any styles, it'd look up and use the style for .container."
From the MDN page on Specifity
Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.
https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
Hence p will override .container no matter what. The inherited style from .container is overwritten
think of the css in this specific case as a target bulls eye.
you start from the most specific pointer to your element in question.
in your example above, it is the p selector since the text is within the p tag wrapper. then going outward from that (the ring right outside the bulls eye, if you will) is the .container div. since the target p is closest to the text you want to color, it inherits that css (color text of blue).
in the example below:
.container {
color: red;
}
p {
color: blue
}
<div class='container'>
i should be red text since im outside the p tag but inside the div container
<p>foo</p>
</div>
you see that the text "i should be red...." doesnt necessarily have a "bulls eye" css, so it goes one ring outside and sees .container and is assigned the color red.
========
now to answer your question about specificity
specificity applies to a case like the example below:
.makeMeBlue {
color: blue;
}
.makeMeBlue.actuallyMakeMeRed {
color: red;
}
<div class="makeMeBlue">i am some random text</div>
<div class="makeMeBlue actuallyMakeMeRed">some more text here</div>
in the above example, you see that make .makeMeBlue has css to make the color of the text blue. however, the second .makeMeBlue div's text color is red. this is because we were more specific about targeting the second element. we used the selector .makeMeBlue.actuallyMakeMeRed utilizing both classes of the element to say "this is the element i want to target specifically and assign this css to".
so instead of the element being like "developers are blue, ok i'll be blue" it sees "hey, someone just said all developers who are named 'jason' are red, and my name is jason and i'm a developer - it is more specific to me, so i'll be red".
i hope that explained specificity a little more clearly.
Currently tweaking a theme and have tried searching for an answer to this question to this! I'm not stuck - but more just want to know the answer out of curiosity.
I understand that
"#" means an id and
"." means a class.
I've also been reading on this post about how you can add specificity to your html/css through combination of elements/ids/classes ie:
a.fancy { color: red; } /*an element that has an anchor and a class = red.*/
However the code I am working on has the following elements that I don't understand:
div.footer {background-color: {{ settings.footer_color }};
Why would you specify "div.footer" as both the div and the class when simply using a "." would suffice? In my mind there would be no point when the class ".footer" could be used without a div?
Hope you can help me work this one out!
div.footer means the element must both BE a <div> and HAVE the class footer.
.footer would trigger for any element with class footer; for example, a <span class="footer".
div.footer means you are targeting only <div> elements with the class .footer.
<div class="footer">This is targeted.</div>
<p class="footer">This isn't targeted, as it isn't a div with the class .footer.</p>
div .footer, however, would target all elements with the class .footer that are descendants from <div> elements.
<div><p class="footer">This is targeted.</p></div>
<section><p class="footer">But this isn't targeted.</p></section>
With the new implementation of html5 <footer> is a legitimate tag just like <div> or <p>. As confusing as it may be the period . before the footer declaration constrains it to a class name instead of the tag.
So in your case: div.footer = <div> with class name footer = <div class="footer>.
There are numerous reasons why you may make such a declaration.
Sample html
<div>
<div class="footer">Footer only</footer>
<div>Div only</div>
<footer>Footer tag; DIFFERENT</footer>
</div>
Example Css
div {
border: 1px solid red;
}
.footer {
background: blue;
color: #fff; /* white font color */
}
Depending on what you want to do, let's use the specific div.footer examples to show what we can do.back
Inheritance
By inheritance, div.footer will inherit "3 properties" -> background, color and border from the div and .footer declarations.
Now you may want to override some of these properties so...
Overriding Property
Use something like div.footer { color: red; } this will override the white color.
Layout Insight
The beauty of css is that you can use declaration to give you "insight" on what the html markup will be laid out as.
Omitting properties I would write the css as follows:
#footer {}
#footer ul {}
#footer ul li {}
#footer p {}
#footer p a {}
The html:
<div id="footer">
<ul>
<li>List 1</li>
<li>LIst 2</li>
</ul>
<p>Hello! Copyright website company name.</p>
</div>
You could then reverse engineer the html through just css because of the descendent character use. This maximizes the power of "cascading".
--
NOow I hope some of this has given you some insight. A few other pointers are this:
Typically a webpage has only one footer. When there is only one of something use the # id selector ALWAYS.
Use classes to not only apply styles to multiple elements but to also provide "meaning to your markup" -> go back to the principle of "layout insight" to understand what I mean.
div.footer should could more simply be .footer Now, it may be necessary to include div just to say "I only want to apply this class to divs only" and in that case go for it. But defining all your declarations with div.someClasName is not all that valuable.
DO NOT use names of tags as classnames. div.div is very confusing - especially if you are programming for a while. Therefore, since <footer> is now a legit tag you shouldn't apply it as a classname. On the other hand "#footer" could be argued differently because it can only exist once in a webpage.
It's about specificity. div.footer is more specific (a div with that particular class) than .footer (any element with that class).
As to when to use one or the other, it really depends on the markup and CSS you are building.
I wondered if there is a better solution than to what I found without changing the html-structure
The HTML structure looks like this
<div class="wrap">
<div class="divider"></div>
<div class="block"></div>
<div class="block"></div>
<div class="divider"></div>
</div>
So there's various DIVs on the same level, what I want to do is to color every fourth block differently, until a divider appears, then it'd have to recount.
I thought something like .block:nth-child(4n) would do the trick, but it actually counts the elements based on the parent, not based on the class.
Here's the JSFiddle to try out.
Block #4 and #8 in each row should be differently colored
http://jsfiddle.net/SKgdH/3/
And this is how I made it sort-of work:
http://jsfiddle.net/SKgdH/1/
What I did was to look for the 4th sibling of the .divider like this .divider + .block + .block + .block + .block
It works, however, I'd have to write the same for the 8th, 12th, 16th, .. block, which doesn't make it automatic anymore.
Is there something like .divider + .block:nth-sibling(4) or .divider + .block:nth-of-class(4)?
Maybe one of you got an idea on how to solve this without changing the source code or using javascript.
Such a pseudo-class would not work because you are expecting it to match elements relative to a different compound selector, which is not how simple selectors work. For example, if you wrote a complex selector that only had a single compound selector with that pseudo-class (and no sibling combinators):
.block:nth-sibling(4n)
Would you expect this to match .block:nth-child(4n), match nothing at all, or be invalid?
It'd be nice to be able to abridge + .block + .block + .block + .block and make it repeat somehow, but unfortunately due to how the selector syntax is designed, it's just not possible.
You'll have to use JavaScript and/or add extra classes to the appropriate elements instead.
The issue here is that :nth-of-type refers to the type of element and both .divider and .block are elements of type <div>.
What you really need is for .divider to be a different type of element from .block.
On that basis, if the only two child elements of <div class="wrap"> are:
<div class="divider">
<div class="block">
I'd be tempted to swap out <div class="divider"> for <hr> - the thematic break element.
Then you can use:
.wrap div:nth-of-type(4)
to style .block.
As explained by BoltClock, you can't do this without JavaScript. If you choose that route (even though you explicitly say without JavaScript), it can be done with jQuery like this:
var counter = 0;
$('.wrap > div').each(function() {
if ($(this).hasClass('divider')) {
counter = 0;
}
else if ($(this).hasClass('block')) {
counter++;
if (counter % 8 == 4) {
$(this).css('background-color','#ff0');
}
}
});
That will color the 4th column in every row yellow.
Can you use the word div to name a div class? or id?
for example:
#div.leftcol
or does it just get seen as
#leftcol
The browser will see that as <div id="div" class="leftcol"></div>
I don't follow what you mean, but I think what you're asking is can you use the word div to apply a class to div elements. If that's what you mean, then yes you can, and you do it exactly as you have shown in your question:
div.leftcol { color: red }
That style would be applied to all elements of type div with class leftcol. Without the div part, the style would apply to any element with class leftcol, regardless of what type of element it is:
.leftcol { color: red }
Edit now the question has been edited...
After the edit to your question, it makes a bit more sense (I think). Your first example would apply to an element with an id of div and a class of leftcol:
<div id="div" class="leftcol"></div>
The second example would apply to an element with an id of leftcol:
<div id="leftcol"></div>
Or if you are simply asking whether div is a some sort of reserved word in CSS, no, it's not, so feel free to use it as an identifier. However, that could get confusing (for example, you could end up with selectors like div.div #div)
can you provide an example?
you can use <div class="leftcol"> left content </div>
and then in your css .leftcol { background:red; }
you can address it either div.leftcol or just simple .leftcol
As in?
<div id="div.leftcol">Some content</div>
While it may work for HTML and Javascript it should cause a problem if you try to style it in a CSS stylesheet. As I am sure you know the following
div.leftcol {
color: #efefef;
}
means "Set the text color to #efefef for any div element that has leftcol as a class name" so it would not work. I have no idea if
div.div.leftcol {
color: #efefef;
}
would work but that is just ugly...