Jax Teller
Jax Teller

Reputation: 1467

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.

Upvotes: 13

Views: 13920

Answers (4)

Temani Afif
Temani Afif

Reputation: 273021

If we think about this differently considering that you want to override width/height then yes you can do it with min-width/min-height:

#my_component {
  min-width:200px;
  min-height:200px;
  background:red;
}
<div id="my_component" class="class_1" style="width: 40px; height: 40px;"></div>

And to be more accurate you can add the max-* version to be sure you have a fixed height/width:

#my_component {
  min-width:200px;
  min-height:200px;
  max-width:200px;
  max-height:200px;
  background:red;
}
<div id="my_component" class="class_1" style="width: 40px; height: 40px;"></div>

Upvotes: 10

James Long
James Long

Reputation: 4736

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.

Upvotes: 1

Dan Scott
Dan Scott

Reputation: 564

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.

Upvotes: 2

Quentin
Quentin

Reputation: 943615

No.

The only way to override a CSS rule without using !important is to use a more specific selector.

No selector is more specific than the style attribute.

Upvotes: 3

Related Questions