Home > Blockchain >  Which method of adding styles, CSS or JS, has the highest specificity?
Which method of adding styles, CSS or JS, has the highest specificity?

Time:04-04

While doing codes something like below:

document.querySelector('input[type=text]').addEventListener('focus', function() {
  document.querySelector('#deletebutton').style.display = 'none'
})
input[type=text]:focus #deletebutton {
  display: block;
}

input[type=text]:not(:focus) #deletebutton {
  display: none;
}
<input type='text'>
<button id='deletebutton'>delete</button>
what is looks like with JS event:

input[type=text]:focus #deletebutton {
  display: block;
}

input[type=text]:not(:focus) #deletebutton {
  display: none;
}
<input type='text'>
<button id='deletebutton'>delete</button>

It seems like JS has more control (higher priority) than CSS does to the HTML button. The input will follow the rule for JS eventListener and ignore the CSS pseudo-class (:focus).

Does this means CSS has less priority than JS?

Or the css focus event is a selector, but JS it is an eventListener where eventListener is more important?

Or I should put the script in the header before the css stylesheet (now i put it in the body)

Or all my attempt is wrong?

Thanks!

CodePudding user response:

CSS gets applied based on the principle that "the most specific rule wins", explained in detail over on https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

When you directly manipulate one, and only one, element's styling, either through JS by working with element.style or through HTML by having a style attribute: that is the most specific you can get. Those values will always "win".

The only exception is if you're directly setting values that you also have regular CSS for, marked as !important. However, if you find yourself needing !important that's a good indication that you've probably modeled your cascade or even your element tree wrong.

  • Related