Home > Enterprise >  Can flexbox force an SVG element to resize?
Can flexbox force an SVG element to resize?

Time:05-26

Context: I would like to my blog a list of projects (as logos with links) that I relied on to build it as an acknowledgment. They will be displayed on a sidebar.

Problem: The SVG logos have each a different initial (default) size. I would like them to expand horizontally preserving the ratio.

I simulated this through the code below, where the <svg> represents a file with a logo

.column {
  display: flex;
  flex-direction: column;
  width: 200px;
  border-style: dashed;
  border-width: 1px;
  gap: 10px;
  flex-grow: 1;
}

.logo {}
<div >

  <div >
    <svg width="50" height="50">
      <rect width="100%" height="100%" fill="green" />
    </svg>
  </div>

  <div >
    <svg width="25" height="50">
      <rect width="100%" height="100%" fill="red" />
    </svg>
  </div>

</div>

I was hoping that flex-grow: 1; would expand the rectangles, to end up with the two of the same width, and the red one twice the height of the green one.

Is it possible for flex to force a resizing of an SVG element?

CodePudding user response:

Like below maybe:

.column {
  display: flex;
  flex-direction: column;
  width: 100px;
  border-style: dashed;
  border-width: 1px;
  gap: 10px;
}

svg {
  width: 100%;
  height: auto;
  display: block;
}
<div >

  <div >
    <svg width="50" height="50">
      <rect width="100%" height="100%" fill="green" />
    </svg>
  </div>

  <div >
    <svg width="25" height="50">
      <rect width="100%" height="100%" fill="red" />
    </svg>
  </div>

</div>

CodePudding user response:

If you replace the width and the height attributes on <svg> with a viewBox attribute, the SVG will take up 100% of the available space.

.column {
  display: flex;
  flex-direction: column;
  width: 200px;
  border-style: dashed;
  border-width: 1px;
  gap: 10px;
  flex-grow: 1;
}

.logo {}
<div >

  <div >
    <svg viewBox="0 0 50 50">
      <rect width="100%" height="100%" fill="green" />
    </svg>
  </div>

  <div >
    <svg viewBox="0 0 25 50">
      <rect width="100%" height="100%" fill="red" />
    </svg>
  </div>

</div>

CodePudding user response:

You can insert the SVG files as src in an <img> and set that to 100% in width.

.column {
  display: flex;
  flex-direction: column;
  width: 200px;
  border-style: dashed;
  border-width: 1px;
  gap: 10px;
  flex-grow: 1;
}

.logo img {
  width: 100%;
}
<div >

  <div >
    <img src="data:image/svg xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI CiAgPHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iZ3JlZW4iIC8 Cjwvc3ZnPgo="/>
  </div>

  <div >
    <img src="data:image/svg xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNSIgaGVpZ2h0PSI1MCI CiAgPHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0icmVkIiAvPgo8L3N2Zz4K"/>
  </div>

</div>

  • Related