Home > database >  How to stop SVG breaking CSS grid layout?
How to stop SVG breaking CSS grid layout?

Time:06-10

Whenever I insert SVG into my grid layout it 1) doesn't center, and 2) breaks the layout of the grid. How do I fix this please, so that the play icon shows in the same way the play text does.

Here's the layout that's breaking:

.body { background-color: hsl(0,0%,10%); color: white; font-size: 32px; }
.center_children { display: flex; justify-content: center; }
.timer
{
width: 12rem; height: 12rem; border-radius: 50%;
background-color: hsl(0, 50%, 50%); 
display:grid; grid-template-rows: 2fr 1fr; gap: 1.5rem;
}
<div >
<br />
<div >
    <div >
        <div >Play</div>
    </div>
    <div >1:39</div>
</div>
<br />
</div>

<br /><br />

<div >
<br />
<div >
    <div >
        <div >
            <svg width="100%" height="100%" viewBox="0 0 100 100" ><polygon points="0,0 75,50 0,100" style="fill:#fff;" /></svg>
        </div>
    </div>
    <div >1:39</div>
</div>
<br />
</div>

CodePudding user response:

Here are the problems in your code:

  • You haven't specified the width and height of both your grid rows and columns, so as the svg grows it pushes the grid out of your intended alignment.
  • fr units are fractions of available space. They will move depending on your content. If you want rows fixed at 33% and 66% then you have to use % not fr.
  • You haven't added justify-content: center to center your columns. You don't need the flexbox.
  • You don't need to specify a viewBox for an SVG if you want the whole image to show. You are not understanding viewport versus viewBox (read https://webdesign.tutsplus.com/tutorials/svg-viewport-and-viewbox-for-beginners--cms-30844).

Here's the code fixed (add a little padding yourself to make things look perfect relative the circle):

.body { background-color: hsl(0,0%,10%); color: white; font-size: 32px; }
.timer
{
width: 12rem; height: 12rem; border-radius: 50%;
background-color: hsl(0, 50%, 50%); 
display:grid; grid-template-rows: 66% 33%; 
grid-template-columns: 5rem;
justify-content: center;
}
<div >
<div >
    <div >
        <svg width="100%" height="100%" ><polygon points="0,0 75,50 0,100" style="fill:#fff;" /></svg>
    </div>
    <div>1:39</div>
</div>
</div>

  • Related