Search code examples
csssvgfirefoxflexbox

Firefox doesn't set width correctly for SVG's parent div


I have an SVG without fixed width and height, it has only viewbox defined. I have one flex container which contains some child divs and inside those childs are the SVG's. With Chrome this works fine and SVG's are set side by side next to each other. But with Firefox those child divs have width 0px and all the SVG's are put on top of each other. How could I make those divs / svgs behave in Firefox same way as Chrome?

I tried the solution where I set the width of the divs in javascript, but I would prefer CSS only solution.

<div class="container">
  <div class="first">
    <svg viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" />
    </svg>
  </div>
  <div class="second">
    <svg viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" />
    </svg>
  </div>
</div>
.container {
  display: flex;
  height: 50px;
}

.first {
  background: green;
}

.second {
  background: yellow;
}

svg {
  width: auto;
  height: 100%;
}

Solution

  • You also have to add width: auto and height: 100% to the parent divs:

    .container {
      display: flex;
      height: 50px;
    }
    
    .first {
      background: green;
    }
    
    .second {
      background: yellow;
    }
    
    svg, .first, .second {
      width: auto;
      height: 100%;
    }
    <div class="container">
      <div class="first">
        <svg viewBox="0 0 100 100">
          <circle cx="50" cy="50" r="50" />
        </svg>
      </div>
      <div class="second">
        <svg viewBox="0 0 100 100">
          <circle cx="50" cy="50" r="50" />
        </svg>
      </div>
    </div>

    Alternatively you can put the SVGs directly in the main container

    .container {
      display: flex;
      height: 50px;
    }
    
    .first {
      background: green;
    }
    
    .second {
      background: yellow;
    }
    
    svg {
      width: auto;
      height: 100%;
    }
    <div class="container">
      <svg viewBox="0 0 100 100" class="first">
        <circle cx="50" cy="50" r="50" />
      </svg>
      <svg viewBox="0 0 100 100" class="second">
        <circle cx="50" cy="50" r="50" />
      </svg>
    </div>