I was working on a project not too long ago where my goal was to add a rich text editor to the platform. We found an open source project to incorporate called TipTap. This made it easy to add all the fanciness to rich text that you’d find like bolding, italicizing, or underlining text. As I was following along with some wireframes, I downloaded a set of SVG’s that we wanted to use as icons for all these different tools inside of our toolbar.
Suddenly I came across an issue that I had never seen before in my life. I start to change the size of my SVG with styled components, inline styles, and adding rules to my sass file. The result was that changing the width and height of my SVG would only cause overflow. So although the SVG never resized, the html element did.
As you can see above, I’m using a cool looking little laptop for this example. All I’ve done was import into my file but after adding some rules to make it smaller, it starts to clip as shown below.
What’s going on here? I should be able to make it smaller or bigger and my SVG should scale to my changes, not clip! After some digging, I found an SVG property that I ignored. I was under the impression that all SVG’s came with the property out of the box but this one did not.
The viewBox property. According to the mdn web docs, the viewBox attribute defines the position and dimension in user space. It’s a list of four number that represent the min-x, min-y, width, and height.
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" />
After some time scratching my head I realized that this attribute was missing from my SVG. Once I added it back, I tested it out with small and large dimensions to see if it scales.
This was actually a fun little problem I came across. I don’t often breakdown SVG’s but this helped me understand them a bit more than I did yesterday. Hopefully this saves someone some time and as always, happy coding!