Jump to content

CSS Specificity page


PawelX

Recommended Posts

https://www.w3schools.com/css/css_specificity.asp

There are two statements on that page that I can't wrap my head around:

1

"Equal specificity: the latest rule counts - If the same rule is written twice into the external style sheet, then the lower rule in the style sheet is closer to the element to be styled, and therefore will be applied:

h1 {background-color: yellow;}
h1 {background-color: red;}"

In what sense is the rule "closer to the element"? It comes last (so it's logical that it overrides any previous rules with the same specificity), but I don't know in what sense it's "closer". 

2

"Contextual selectors are more specific than a single element selector  - The embedded style sheet is closer to the element to be styled."

I've no idea what the underlined statement means in the context. How is a selector in an external file a "single element selector"? Doesn't the embedded selector also select a single element (the same one)? And how is that related to being "closer"?

THANK YOU

Link to comment
Share on other sites

1) It's the order of precedence, cascading style sheet, meaning precedence will always cascade down to the lowest, unless the previous has a higher precedence because it's more specific, and uses a identifying selector such as class, Id or it references a class, Id  of parent elements or even its parent elements tagname itself.

a div element selector div{} is the lowest precedence you can have. A section parent with div i.e section div {} increases precedence it's more specific, then you can start including class div.classname{} will specifically target div with class 'classname', this has higher precedence over the previous mentioned, using a unique id will give it even higher precedence and so on.

2) again precedence! Inline styling on element is the closest you can get, so it has higher precedence, changing the styling of that, is difficult unless !important (not advisable) is used within embedded styling between <head>...</head> or external stylesheet. So to have more control, avoid element inline styling.

Embedded styling second level of precedence with external stylesheet third, but the rules still apply from (1) IF the selector is more specific with higher precedence over those following it, except for inline element styling (unless the bad !important is used),  It will overide those specific property set styling.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...