I am trying to display a grid of SVGs using CSS grid. Something simple like this example, which is just divs, no SVGs yet. This works fine.
#wrapper {
display: grid;
grid-gap: 2px;
grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
width: 650px;
.child {
background-color: green;
aspect-ratio: 2/3;
}
}
<div id="wrapper">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
Now if I add an SVG inside one of the divs, it messes up the alignment:
#wrapper {
display: grid;
grid-gap: 2px;
grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
width: 650px;
.child {
background-color: green;
aspect-ratio: 2/3;
}
}
<div id="wrapper">
<div class="child"></div>
<div class="child"><svg viewBox="0 0 400 600" style="background-color: black"><circle r="45" cx="50" cy="50" fill="red" /></svg></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
Somehow it's adding a little extra padding to the bottom of the "child" div that contains the SVG, but I can't figure out why that's happening or how to prevent it. Any ideas?
SVG's are considered inline
elements, and so they have a height defined by line-height (which might be inherited).
The answer here goes in much more detail: Inline elements and line-height
So the options to fix would be to set your svg
elements to display: block;
. Or adjust the line-height
of these elements based on the size of the SVG (or to line-height: 0
, but that has always felt kind of hacky to me).