0

I have an SVG in an absolutely positioned div. The div is a grid and has a width and height set.

The SVG has a width and height of 100% and has overflow set to visible.

if (for example) the parent div is 150 x 75, I would expect the svg to be 150 x 75, and in Chrome this is indeed the case

However in firefox it is not (not sure about safari?!), it seems to make the height the default for svgs (i believe svgs are naturally 300x150 if no dimensions given)

<html>
<head>
<style>
  body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

svg {
    background-color: green;
    height: 100%;
    width: 100%;
    overflow: visible;
}

#parent{
  position: absolute;
  left: 30px;
  top: 50px;
  width: 150px;
  height: 75px;
display: grid;
}
</style>
</head>
<body>

<div id="parent">
<svg></svg>
</div>
</body>
</html>
user2445278
  • 808
  • 1
  • 8
  • 15

1 Answers1

1

The issue is due to the fact that you are using percentage value inside grid and the percentage will be relative to grid track not the grid container. This will create a random behavior since we didn't explicitely define the size of the tracks

An easy fix is to define a grid-template-rows in addition to the height with the same value:

body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

svg {
  background-color: green;
  height: 100%;
  width: 100%;
  overflow: visible;
}

#parent {
  position: absolute;
  left: 30px;
  top: 50px;
  width: 150px;
  height: 75px;
  grid-template-rows: 75px; /* added this*/
  display: grid;
}
<div id="parent">
  <svg></svg>
</div>

Similar question: Why is my Grid element's height not being calculated correctly?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • I guess the similar question is actually a perfect duplicate – Temani Afif Jun 25 '19 at 14:55
  • thanks for the response. I find it interesting that if its a div on the inside(not an svg) it works as expected, also interesting why we don't get similar behavior with the width (I havn't set a grid-template-column), or in fact see the same behavior at all in Chrome or Safari – user2445278 Jun 25 '19 at 15:10
  • @user2445278 first, width and height are different, height is defined by content and width is generally defined to be 100% for block element so we *almost* never have issue with width because we can easily find it. Secondly, it's logical to not have issue with div because it's an empty element without any default height unlike SVG but you will probably have the same issue if you consider an image for example or a div with some content that exceed the container height. – Temani Afif Jun 25 '19 at 15:23
  • @user2445278 and yes we don't have the same behavior because it's something very particular and not all the browser will handle it the same but we, at least, know how to force the behavior to be the same. – Temani Afif Jun 25 '19 at 15:24