A-Bro
A-Bro

Reputation: 103

SVG React Component will not center

I have an svg in my site that I wanted to animate, so I changed the tag from img to svg for the animation to work.

Unfortunately, this led me to the issue of properly centering my SVG in my window. I cannot do this responsively

I have created a sandbox to reproduce the issue for you.

https://codesandbox.io/s/tender-fast-xdjzk

What I have tried includes:

 .globe-svg {
   position: absolute
   transform: (-50%, -50%)

 .App {
    display: flex,
    align-items: center,
    justify-content: center

The closest I have been able to get to what I want is using position: relative and setting left to a certain percentage but this is not responsive at all, so left: 50% would work in one viewport width only.

Upvotes: 0

Views: 1942

Answers (1)

A-Bro
A-Bro

Reputation: 103

Credit goes to Robert Longson and Toni Michel Caubet for helping me piece this together but I figured it'd be best to post the solution I came up with here since the discussion was mainly in the comment thread.

First I will address my errors:

  1. Invalid ViewBox

As Robert pointed out, I misunderstood how to use viewBox and as a consequence used incorrect values. To help resolve my issue, I set my viewBox to 0 0 380 380 and adjusted height and width accordingly

    <svg
      width="380px"
      height="380px"
      viewbox="0 0 380 380"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={`globe-svg ${classActive}`}
    >
  1. HTML, Body reset for App 100% height

This is necessary for the app to be at 100% height and have an effect on the rest of the element's CSS.

html,
body {
  height: 100%;
  margin: 0;
}

Main Changes to App and Svg CSS

To actually center the SVG after making these key changes, I used a combination of flexbox and transform:translate(). I tried this earlier before posting, but due to the not having made two changes I needed to do above at that time period, it could not work properly as a solution beforehand.


.App {
  font-family: sans-serif;
  text-align: center;
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.globe-svg {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

Thank you again for your help!

Upvotes: 1

Related Questions