Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override inline CSS from CSS file without !important

I have an angular component, that generates inline style attributes in the resulting HTML.

Example :

<my-component></my-component>

The HTML of that component is:

<div id="my_component" class="class_1" style="width: 40px; height: 40px;"></div>

Is there a way to override the width/height of my_component from external CSS file? I tried many selectors, I'm always getting overridden by the inline style...

!important is working, but I would like to know if there is another way than use !important.

like image 839
Jax Teller Avatar asked Dec 19 '18 15:12

Jax Teller


People also ask

How do you override CSS inline?

The only way to override inline style is by using ! important keyword beside the CSS rule.

How do I override existing CSS?

To override the CSS properties of a class using another class, we can use the ! important directive. In CSS, ! important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.

How do you override external CSS with internal CSS?

It works kind of counter-intuitively, so just to explain further: inline styles override internal CSS, and internal CSS overrides external CSS files, and external CSS files override browser defaults. One way to think about it is like layers. The “closer” the style is to the element, the higher precedence it has.

Does important work with inline CSS?

important Is Not Supported By Inline Styles.


2 Answers

There used to be a bug where a selector containing 256 would override an id. There may be some upper limit to the counter and going over that would cause an override to the next value (a selector of 256 ids would override an inline style).

I think the 256 classes bug was fixed and I don't know whether this was done by increasing the necessary number of classes or putting in place something to prevent it ever happening again.

From a purely academic perspective, it may be possible to override an inline style without using !important but it would be more of a a bug exploit as opposed to part of the spec / a good idea.

like image 187
James Long Avatar answered Oct 09 '22 04:10

James Long


CSS Specificity works in a hierarchy

  1. !important overrides
  2. Inline Styles
  3. ID's - HTML: id="blah", CSS: #blah
  4. Classes - HTML: class="foo", CSS: .foo
  5. Elements and pseudo-elements (:before, :after).

you can read more on it here

but as others have said, in short, no.

like image 28
Dan Scott Avatar answered Oct 09 '22 05:10

Dan Scott