Resize SVG in flex+grid container

by darkstarsys

HTML

<h3>
Show fit to width and height: SVG stays within bounds
</h3>
<button onclick="resize('top1')">
Resize container taller/shorter
</button>

<div id="top1" class="top">
<div class="inner1 grid">
<svg class="svg" height="100%" width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 points="0,10 20,10 10,0" />
    <polygon fill=green stroke-width=0 points="0,10 20,10 10,5" />
</svg>
</div>
</div>

<h3>
Example 2, SVG wrapped in div, doesn't scale properly:
</h3>
<button onclick="resize('top2')">
Resize taller/shorter
</button>

<div id="top2" class="top">
<div class="inner1 grid" style="border: 1px solid green">
<div class="outer-wrapper" style="border: 1px dashed yellow">
<div class="wrapper">
<svg class="svg" height="100%" width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 points="0,10 20,10 10,0" />
    <polygon fill=green stroke-width=0 points="0,10 20,10 10,5" />
</svg>
</div>
</div>
</div>
</div>

CSS

.top {
  width: 30vw;
  height: 50px;
  border: 1px solid blue;
  display: flex;
  flex: 1 1 auto;
}
.svg {
  margin: auto; /* center */
  display: block;
  border: 1px dashed red;
}
.grid {
  display: grid;
  grid-template-columns: 1fr;
  column-gap: 10px;
  align-items: center;
  width: 100%;
}
.wrapper {
  width: 100%;
  height: 100%;
}
.outer-wrapper {
  display: block;
}

JavaScript

function resizeElt(id, h) {
  const elt = document.getElementById(id)
  elt.style.height = h
}
let large = false
function resize(id) {
  large=!large
  resizeElt(id, large ? '100px' : '50px')
}