Is an attribute selector for the ID attribute less specific than an ID selector?
Asked Answered
S

2

3

What do I need to do to give the [id^=value] selector the same specificity as a regular ID, and why isn't it equal or greater already? (considering that I gave it html as well)

html div[id^="blue"] {
    background-color: blue
}

#blue4 {
    background-color: red
}

jsfiddle: http://jsfiddle.net/bjwe6yr0/1/

Stonefish answered 30/9, 2015 at 13:57 Comment(3)
This is a matter of how CSS is designed. A ID selector (#) has a higher specificity than class and attribute selectors.Ryannryazan
So, though it's selecting IDs, it's not actually being credited as an ID? And I'm reviewing your link nowStonefish
div[id^="blue"] is an attribute selector. you could also address [data-something] in the same fashion. Also if you address the id in your example, you do not use the dedicated id selector.Ryannryazan
G
5

An attribute selector will always be less specific than an ID selector; its specificity value does not change based on the attribute name. Selectors only maps specific attribute names to class selectors and ID selectors; an attribute selector is a generic concept and does not contain any such mappings.

The only way for a complex selector to have ID specificity is if it contains one or more ID selectors. Implementation limits aside, it is theoretically not possible to override even a single ID selector with any number of attribute selectors or any other type of simple selector.

Here is how your two selectors compare:

/* 1 attribute, 2 types -> specificity = 0-1-2 */
html div[id^="blue"] {
    background-color: blue
}

/* 1 ID                 -> specificity = 1-0-0 */
#blue4 {
    background-color: red
}

Even the addition of html doesn't help because it's just a type selector. Change it to :root and you get a pseudo-class which is equally specific to an attribute selector, and thus still less specific than an ID.

Grus answered 30/9, 2015 at 14:10 Comment(0)
O
2

You may consider the not() selector in order to append a random ID and you will then have a higher or the same specifity since the specifity of not() is equal to the specifity of the selector inside it:

html body div[id^="blue"]:not(#randomID) {
  background-color: blue
}

#blue4 {
  background-color: red
}

div {
  height: 50px;
  width: 50px
}
<div id="blue1"></div>
<div id="blue2"></div>
<div id="blue3"></div>
<div id="blue4"></div>
Omission answered 31/5, 2018 at 21:53 Comment(1)
Should be the correct answer because it solves the problem.Besprinkle

© 2022 - 2024 — McMap. All rights reserved.