volna
volna

Reputation: 2610

Make svg element adapt to container dimensions

I've the following SVG path that is intended to be used as a border of any possible width and height. But currently, I am struggling with the following 2 points and appreciate a lot if some can share some ideas :-)
1. Is it possible to detach SVG from the viewBox and adapt to parent dimension?
2. Is it possible to detach SVG stroke width and always be as defined? (4px)

.c500x200 {
  width: 500px;
  height: 200px;
}

.c200x600 {
  width: 200px;
  height: 600px;
}

svg {
  width: 100%;
  height: 100%;
}

svg path {
  stroke-width: 4px;
  stroke: #d22f2c;
  fill: none;
}
<div class='c500x200'>
  <svg data-name="Layer 1" viewBox="0 0 357.5 248" xmlns="http://www.w3.org/2000/svg">
  <defs>
  </defs>
  <path transform="translate(-289 -320)" d="M623,565.5H291.5v-243h341v231s-1,12,14,12"/>
  </svg>
</div>

<div class='c200x600'>
  <svg data-name="Layer 1" viewBox="0 0 357.5 248" xmlns="http://www.w3.org/2000/svg">
  <defs>
  </defs>
  <path transform="translate(-289 -320)" d="M623,565.5H291.5v-243h341v231s-1,12,14,12"/>
  </svg>
</div>

Upvotes: 1

Views: 437

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

Is it possible to detach SVG from the viewBox and adapt to parent dimension?

The viewBox is the way you get an SVG to adapt to a parent's dimensions. What I think you are asking is whether it is possible to get a viewBox to stretch to fill a parent container.

The answer is yes. You can do that using preserveAspectRatio="none". But note that this stretches the scale of the shape. So curves in the shape will be distorted. See below.

Is it possible to detach SVG stroke width and always be as defined? (4px)

Yes. You can set vector-effect: non-scaling-stroke on the path elements. See below.

.c500x200 {
  width: 500px;
  height: 200px;
  background-color: linen;
}

.c200x600 {
  width: 200px;
  height: 600px;
  background-color: linen;
}

svg {
  width: 100%;
  height: 100%;
}

svg path {
  stroke-width: 4px;
  stroke: #d22f2c;
  fill: none;
  vector-effect: non-scaling-stroke;
}
<div class='c500x200'>
  <svg data-name="Layer 1" viewBox="0 0 357.5 248" preserveAspectRatio="none">
  <defs>
  </defs>
  <path transform="translate(-289 -320)" d="M623,565.5H291.5v-243h341v231s-1,12,14,12"/>
  </svg>
</div>

<div class='c200x600'>
  <svg data-name="Layer 1" viewBox="0 0 357.5 248" preserveAspectRatio="none">
  <defs>
  </defs>
  <path transform="translate(-289 -320)" d="M623,565.5H291.5v-243h341v231s-1,12,14,12"/>
  </svg>
</div>

Upvotes: 2

Related Questions