Skip to content

[css-specificity] Add specificity property modifier (replace !important) #3890

Closed
@BennyHinrichs

Description

@BennyHinrichs

Currently there is the ability to hoist a property's specificity beyond that of its selector via !important. This often leads to people writing labyrinthine selectors, then slapping !important on the properties to override a previous developer's styles.

What if where you put !important, you could put !specificity(10)? What if in developer tools, every rule/property showed its specificity in number form? This would effectively change the esoteric nature of specificity to something much easier to determine and comprehend. It would be very clear to see, "Oh, my rule isn't being applied because it's of specificity 2 and there's another one of specificity 5."

Let's say that you want to ensure your .hidden class always hides the element it's applied to. In your stylesheet you could have something like:

:root {
  --sp-low: 1;
  --sp-med: 10;
  --sp-high: 20;
}

.hidden {
  display: none !specificity(var(--sp-high));
}

Or imagine switching between light and dark modes. All you would have to do is change the specificity variable of the dark to be greater or less than that of the light.

:root {
  --sp-light: 1;
  --sp-dark: 0;
}
document.getElementById('themeToggle').addEventListener('change', ({target}) => {
  document.documentElement.style.setProperty('--sp-dark', target.checked ? 2 : 0);
}

Or say you want to set the specificity for an entire selector:

.nav {
  all: !specificity(2);
}

It would make specificity akin to how z-index is now. If you can't see your element, it's pretty straightforward to compare z-indices. One potential issue is that it opens specificity up to abuse (e.g. !specificity(100000000). That being said, I think it's mild compared to the abuse it currently suffers. I personally prefer a straight number over trying to parse my way through selector chains and !importants.

EDIT I know that there are 5 levels of specificity. This proposal is specifically being able to assign a number to !important.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions