Positioning HTML5 SVG in the center of screen

To center an SVG element horizontally on the screen, you can use CSS properties like margin and display. This technique works by making the SVG a block-level element and setting automatic left and right margins.

CSS for Centering SVG

Apply the following CSS to center your SVG element:

#svgelem {
    margin-left: auto;
    margin-right: auto;
    display: block;
}

HTML SVG Element

Here's the SVG element that we'll center using the above CSS:

<svg id="svgelem" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
    <circle id="redcircle" cx="50" cy="50" r="50" fill="red" />
</svg>

Complete Example

Here's a complete HTML page demonstrating how to center an SVG element:

<!DOCTYPE html>
<html>
<head>
    <style>
        #svgelem {
            margin-left: auto;
            margin-right: auto;
            display: block;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <h2>Centered SVG Element</h2>
    <svg id="svgelem" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <circle id="redcircle" cx="100" cy="100" r="50" fill="red" />
    </svg>
</body>
</html>

How It Works

The centering technique works through these CSS properties:

  • display: block - Makes the SVG a block-level element that takes up the full width available
  • margin-left: auto and margin-right: auto - Distributes the remaining horizontal space equally on both sides

Alternative Method: Using Flexbox

You can also center SVG using Flexbox by applying CSS to the parent container:

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

Conclusion

The margin: auto method is the most straightforward way to center SVG elements horizontally. For both horizontal and vertical centering, consider using Flexbox on the parent container.

Updated on: 2026-03-15T23:18:59+05:30

393 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements