This week I would like to talk about one very interesting but important aspect of CSS.
Now let me give you a very simple question and you guess the answer.
If I type below in html:
<svg width=“200px” height=“300px”>…</svg>
and set the below styles in external css file:
svg {
width: 400px;
height: 500px;
}
what would be the final width and height of svg?
If you say 200px and 300px, then buy me a coffee because you are wrong.
If you say 400px and 500px, then buy me a coffee too because you are right.
What? How? Why?
Let’s see the order of styles in cascade below.
User Agent Styles < Presentation Attributes < External Styles < Document Styles < Inline Styles < Animation < Override Styles < Computed Styles
The left is overwritten by right. That means the “Presentation Attributes” are overwritten by all other styles except the “User Agent Styles”.
Now if we go back to the question above, the width and height of SVG count as low-level “author style sheets” like the “Presentation Attributes”.
That’s why it is overwritten by other styles including the external styles.
And it is important to understand this if you are dealing with svg (especially inline svg). Because for whatever reason, such as very low internet connection, if CSS is not loaded, the SVG images without width and height set in the html code will cover the entire viewport.
To avoid this issue, you always need to set the width and height in svg in html and set the proper (responsive) width and height in CSS overwriting the width and height in html. In that way, when the CSS is not loaded properly, there is still a fallback.
Hope it helps you when you deal with svg and as always if you have any questions, please feel free to let me know.