I have a tag which I need to be styled in a specific way, overriding the style we have for I can either put the all style attributes in the tag so it will override all other styles, or I could create a class and set all the attributes to !important.
I want to know which would be considered the best way of doing it, or if I'm going about this the wrong way. There are four attributes that I'm overriding.
Thanks
CodePudding user response:
What you're dealing with is an issue called specificity which is a pain for a lot of developers. There's a good article on MDN and something a little less deep but easier to understand here. There's a good video from the perennially excellent Kevin Powell (he's well worth a follow)
If you can avoid using !important then do so as it creates all sorts of problems later, especially when you get two rules, both with !important and you're then scratching your head wondering which one is, er, 'importanter'.
There's several ways you can increase the specificity of a rule inclding using the use of the :is pseudo selector. To find out which rule wins use this handy tool
CodePudding user response:
Here are some examples.
Doing style
on all
<h1 style="color: white;">this is hard to see</h1>
<h1 style="color: white;">hard to see again</h1>
<h2 style="color: white;">again</h1>
<h2 style="color: white;">last</h1>
Uses up a bit of space.
Using class
CSS code
.hardToRead {
color: white
}
HTML code
<h1 >1</h1>
<h1 >2</h1>
<h1 >3</h1>
<h1 >4</h1>
The class is better since you don't have to copy paste all the time. These are my personal decisions.
CodePudding user response:
I use !important when I need specific classes to override normal styling, for example for active elements. I don't see anything wrong with it used this way.
I never use inline styling unless I set it with JavaScript after the document has loaded. (Or I'm just testing something and I am so lazy I don't wanna scroll to the CSS.)