Home > Software design >  What are the best practices when it comes to dynamically resizing SVG elements?
What are the best practices when it comes to dynamically resizing SVG elements?

Time:10-08

I've been working on the Order Summary Component challenge from FrontEnd Mentor and am a little confused about dynamically resizing <svg/> elements. Just want to make sure I”m doing things correctly as I don’t know much about CSS.

My questions are as follows:

  1. I’m placing the background pattern as a sibling to the card component, setting the container to position: relative and the .background div to position: absolute; inset: 0;. Is this the correct method to float a background image behind a card? Or should I be going about it differently?
  2. I set the svg viewbox to match the provided width and height of the element and removed the width and height (from width="450" height="220" to viewbox="0 0 450 220). I then set the .background div to overflow: hidden; which clips the pattern as the viewport is resized horizontally. Is this correct? Or should I be trying to dynamically resize the svg so that the pattern scales with the container width in addition to the height?
  3. When I zoom into the card I get a 1px gap between the svg element and the card. Why is that? I've added a solid border to see what’s going on with the box model of the card. Should I make the svg slightly larger using the viewbox attribute? Am I splitting hairs here? Does this even matter? It looks fine at 100% zoom but shows up with 110%, 125%, 150%, 175%, and then disappears again at 200%.

CodeSandbox Link

Thanks in advance!

CodePudding user response:

I think you've done a good job there, congratulations.

For 1., my 2 cents is that inset: 0; is a shortcut for top: 0; left: 0; bottom: 0; right: 0;, and this later has broader compatibility.

For 2., I think you're good.

Finally, the last problem, which is the most difficult to solve, has been discussed as sub pixel rendering of SVG. There is a nice compromise workaround for your case: set the article's background-color: rgb(30, 31, 205);, and the section.card-content's background-color: white;. This will fix the zoom for any percentage value (or else, you could try to tweak the width/height and viewBox and some of the zooms will be fixed, but not all. This workaround fixes all).

Edit

To make the svg element behave correctly regarding space around it, apply display: block; style to it.

  • Related