Search code examples
csscss-selectorscss-specificity

Why does the inline stylesheet's 'img' element styles override the inline style on `img` tags?


My issue is that I need the code snippet below to work, but for some reason the Internal stylesheet's element styles (img {height: !important;}) are overriding the inline style on the img tag (style="height:200px;). Why?

Am I mistaken in the CSS order or processing and inheritance? Am I missing something else?

Code Sample

img { height:auto !important }
<img src="https://placehold.it/200x200" width="200" height="200" align="left" border="0">
<img src="http://placehold.it/1x1" height="200" width="9" alt="" align="left" border="0" style="height: 200px;">
<p>Lorem Ipsum cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras tortor turpis, iaculis eu convallis a, pellentesque vitae enim. Fusce commodo vehicula nulla, sit amet congue lacus adipiscing a. Vivamus at convallis nibh. Proin felis turpis, aliquet eu arcu aliquam, accumsan consectetur justo. Vestibulum sit amet arcu quis neque gravida vulputate ut quis sem. Curabitur a metus lacus. Mauris non dolor vitae massa viverra lobortis ut convallis diam. Fusce eu tempor dolor, vitae imperdiet ipsum.</p>

Other notes

I know I could add !important to the img to make it work, but why do I have to? I also know that this is not ideal code and align is deprecated. However the end medium is an HTML email so I need to use less-than-ideal code.


Solution

  • Selector specificity and !important notwithstanding, inline style declarations have higher priority than any author declarations regardless of their selector:

    1. Inline style declarations with !important
    2. Author stylesheet declarations with !important
    3. Inline style declarations
    4. Author stylesheet declarations
    5. UA styles

    It doesn't matter if the selector matching the element with an inline style attribute contains a [style] attribute selector.

    What you have is a height: auto !important overriding a height: 200px inline style. Without the !important token the inline style would take precedence. That's all.

    See also: Relationship between !important and CSS specificity