Search code examples
csssvgflexbox

SVG with height 100% will never shrink below 150px


I'm trying to create a SVG which stretches (in height) to a paragraph with variable height next to it.

Currently I have the following working example code which works as long if the paragraph is bigger then 150px. As soon as the paragraph is less in height, the SVG stops shrinking.

<div style="display: flex">
  <div>
    <svg style="display:block;width: 40px;height:100%">
      <line x1="20" y1="0" x2="20" y2="100%" stroke-width="1" stroke="black"></line>
    </svg>
  </div>
  <div style="height: 300px;border:1px solid">
    This paragraph is 300px, the svg will stretch accordingly
  </div>
</div>

<br><br><br><br>

<div style="display: flex">
  <div>
    <svg style="width: 40px;height:100%">
      <line x1="20" y1="0" x2="20" y2="100%" stroke-width="1" stroke="black"></line>
    </svg>
  </div>
  <div style="height: 50px;border:1px solid">
    This paragraph is 50px, the svg will not shrink below 150px
  </div>
</div>

This can't be solved with javascript, it should be responsive. the SVG is in practice a lot more complicated and cannot be replaced with a simple border-left: 1px solid black


Solution

    • Set your viewBox accordingly, I do not know the userSpaceOnUse (min x min y width height) of your SVG, let's say viewBox="0 0 100 100".

    • Remove width and height attributes.

    • Set the style attribute to 100% width and 100% height.

    • override the default xMidYMid value by setting preserveAspectRatio="none"

    Resulting svg should look like this:

    <svg preserveAspectRatio="none" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="width:100%;height:100%;">