0

I want to display a rectangular SVG between two vertically aligned DIVs, so that the SVG takes up as much space as possible (but keeps its aspect ratio). As the SVG itself is dynamically generated, I have to use the <svg> HTML tag to include it (and i.e. can't use an <img> tag).

So I tried to use flexbox, but the SVG doesn't stick to the rules and gets too large:

html, body, .parent {
  height: 100%;
}

.parent {
  display: flex;
  flex-flow: column nowrap;
}

.contentSVG {
  flex-grow: 1;
}
<div class="parent">
  <div class="contentA">
    content A
  </div>
  <div class="contentSVG">
    <!-- arbritrary SVG -->
    <svg viewBox="0 0 10 10">
      <circle cx="5" cy="5" r="5" fill="red" />
    </svg>
  </div>
  <div class="contentB">
    content B
  </div>
</div>

If I replaced the SVG with some other content the example works as expected.

Do you have any idea how I can realize this without any JS involved?

muffel
  • 7,004
  • 8
  • 57
  • 98
  • Please add a border to `[class ^="content"]` to understand what happens. All those divs are as wide as the window and the svg will take all the width available. I suppose you will need to give `[class ^="content"]` a width – enxaneta Oct 09 '19 at 16:04

1 Answers1

2

You need to add width:100%;height:100% to the SVG and min-height:0 to the parent to allow the shrink effect

html, body, .parent {
  height: 100%;
  margin:0;
}

.parent {
  display: flex;
  flex-flow: column nowrap;
}

.contentSVG {
  flex-grow: 1;
  min-height:0;
}
svg {
  width:100%;
  height:100%;
}
<div class="parent">
  <div class="contentA">
    content A
  </div>
  <div class="contentSVG">
    <!-- arbritrary SVG -->
    <svg viewBox="0 0 10 10">
      <circle cx="5" cy="5" r="5" fill="red" />
    </svg>
  </div>
  <div class="contentB">
    content B
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Is there any way to get your (otherwise great) answer to work with Apple Safari (iOS & Desktop)? Right now the downscaling doesn't work with the most recent versions. – muffel Oct 14 '19 at 09:33
  • @muffel what is the issue you are facing? – Temani Afif Oct 14 '19 at 09:43
  • while the `contentSVG` div shrinks properly (can be visualized by e.g. setting a background color), the SVG itself grows over its boundaries: https://postimg.cc/Zv5tKQfB – muffel Oct 14 '19 at 09:46
  • @muffel this is due to height:100% not being resolved correcty. Instead of it add `display:flex` to `.contentSVG `. It will make the element stretched by default which is equivalent to height:100% – Temani Afif Oct 14 '19 at 11:32
  • Thanks, but I can't get it to work. If I added `display:flex` to `.contentSVG`, the SVG gets a size of 0 height and width. Maybe I got something wrong, could you please add this change to your answer the way you meant it? – muffel Oct 14 '19 at 11:41