0

I have a rect that's 200 by 200px which I want to center in my svg element. So I followed the flex styling I saw on other SO post (i.e. display: flex; align-items: center; justify-content: center;). However as you can see the rectangle is not centered, but the text is.

Note: I am not allowed to use Javascript and can only hand in an HTML doc so this is why I am doing everything in HTML

<svg height="200" width="100%" fill="red" style="display: flex; align-items: center; justify-content: center;">
    <g>
      <rect x="0" y="0" height="200" width="200" style="fill: red"/>
      <text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-family="Palantino" fill="black">Text</text>
    </g>
  </svg>
14wml
  • 4,048
  • 11
  • 49
  • 97
  • haha you're right ^^; realized i wasn't thinking and i meant javascript – 14wml Feb 08 '18 at 18:40
  • Does this answer your question? [How to style SVG with external CSS?](https://stackoverflow.com/questions/18434094/how-to-style-svg-with-external-css) – ikonuk May 18 '22 at 14:55

2 Answers2

3

SVG doesn't get its styling from CSS.

You'll have to do it the svg way:

    <svg height="200" width="100%" fill="red" style="display: flex; align-items: center; justify-content: center;">
      <g>
        <rect  transform="translate(-100)" x="50%" y="0" height="200" width="200" style="fill: red"/>
        <text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-family="Palantino" fill="black">Text</text>
      </g>
    </svg>

Explanation

We moved the square 50% to the left by toggling its x axis and then subtracted half of its width (100px) using a translate transformation, which makes it a perfect center.

silicakes
  • 6,364
  • 3
  • 28
  • 39
0

I don't think you can use Flex to layout shapes and things in SVG. You could, however, layout the SVG itself using Flex and HTML.

Here is an example:

<div style="height: 200px; width: 100%; display: flex; align-items: center; justify-content: center;">
  <svg height="200" width="200" fill="red">
    <g>
      <rect x="0" y="0" height="200" width="200" style="fill: red"/>
      <text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-family="Palantino" fill="black">Text</text>
    </g>
  </svg>
</div>
Jonathan Urzúa
  • 156
  • 2
  • 4