0

When I have an image with attributes width and height my css is overriding these attributes but if I have inline-styles with width and height my external css doesn't override the inline-styles. Why?

Example code without added CSS:

<img class="pic" src="http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg" width="100" height="100" />

Example code with added CSS:

.pic {
  width: auto;
  height: auto;
}
<img class="pic" src="http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg" width="100" height="100" />

Example code with inline style:

.pic {
  width: auto;
  height: auto;
}
<img class="pic" src="http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg" style="width: 100px; height: 100px" />
Anthony
  • 1,439
  • 1
  • 19
  • 36
  • I understand that. My question was aimed more towards why external CSS overrides inline attributes. – Anthony Jun 21 '16 at 19:21
  • 2
    That's interesting. I'd want this behavior though otherwise you'd never be able to adjust the size of image externally for css media queries, etc. Having a height and width attr does reserve the space in the browser though, so I guess you can have your cake and eat it too. – Dan Weber Jun 21 '16 at 19:30
  • My assumption is that it writes the attributes as non-inline CSS then the external CSS comes after and overrides the CSS attribute selector. – Anthony Jun 21 '16 at 19:49
  • 1
    You find your answer in the dupe link I commented – Asons Jun 21 '16 at 20:00
  • 3
    According to [Specificity @ MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity), "Inline styles added to an element (e.g., style="font-weight:bold") always overwrite any styles in external stylesheets and thus can be thought of as having the highest specificity." The `width` and `height` attributes "are translated to the corresponding CSS rules with specificity equal to 0.. [and] may therefore be overridden by subsequent style sheet rules" -[W3](https://www.w3.org/TR/CSS21/cascade.html#preshint). – showdev Jun 21 '16 at 20:02
  • Thank you @LGSon! That definitely answered my question. – Anthony Jun 21 '16 at 20:04

1 Answers1

1

For override a property like "width" used directly in the html tag on this way "div style="width: 100" is necessary that you put !important after your css code, for example something like this:

.pic {
   width: auto!important;
   height: auto!important;
}
  • 1
    Thanks for the response. I am already aware of this. It is also not recommended to do this, unless absolutely necessary. My question was more geared towards: why does external CSS override inline attributes. – Anthony Jun 21 '16 at 19:58