Resize SVG in flex container
by darkstarsys
HTML
<h3>
Show fit to height:
</h3>
<button onclick="resize('top')">
Resize larger/smaller
</button>
<div id="top">
<div class="bordered">
This is div 1
</div>
<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" />
</svg>
<div class="bordered">
This is Div 2
</div>
</div>
<h3>
Show fit to width (resize browser to see it fit to height too):
</h3>
<button onclick="resize('top2')">
Resize larger/smaller
</button>
<div id="top2">
<div class="bordered">
This is div 1
</div>
<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" />
</svg>
<div class="bordered">
This is Div 2
</div>
</div>
CSS
#top {
width: 90vw;
height: 50px;
border: 1px solid blue;
display: flex;
flex: 1 1 auto;
}
#top2 {
width: 10vw;
height: 15vh;
border: 1px solid blue;
display: flex;
flex: 1 1 auto;
}
.bordered {
border: 1px solid green;
}
.svg {
margin: auto; /* center */
display: block;
border: 1px dashed red;
}
JavaScript
function resizeElt(id, h) {
const elt = document.getElementById(id)
elt.style.height = h
}
let large = false
function resize(id) {
if (large) {
large = false
resizeElt(id, '50px')
} else {
large = true
resizeElt(id, '100px')
}
}
//window.onload = () => {resizeTop(100)}