Howard P
Howard P

Reputation: 258

Aligning an SVG element with left hand side of page

I've started tooling around with SVG as it looks really promising.

I can't quite understand how to align the elements, however. I'm currently trying to make a sample page with a large title that sticks to the left-hand side of the webpage and is vertically centered.

I've set something up, but when the width of the page changes, the SVG moves into the left-hand side of the page instead of just staying there (image below).

A screenshot of the issue enter image description here

I'd like to know how I can fix this, plus why exactly SVG does this. I've set the viewbox and the text element's X value to x="0" which I'd imagine would fix it. I don't understand a lot about SVG so forgive me for novice mistakes.

Here's my code in an MCVE.

<html>
    <header>
        <style>
        /* Visual styling, adds color, font, etc. ----------- */
        body{
          background-color: #121212;
          font-family: "Segoe UI";
        }
        /* Actual structured styling, grid, margin, etc. -------- */
        svg{
          width: 100%;
          height: 100%;
        }
        #mainTitle{
          font-weight: 200;
          font-size: 20px;
          letter-spacing: 2px;
          fill: #d8d8d8;
        }
        </style>
    </header>
    <body>
        <svg viewbox = "0 0 200 200">
            <text x = "0" y = "100" id="mainTitle" text-anchor="middle"> Sample Text </text>
        </svg>
    </body>
</html>

If you know of any good learning resources (not W3) for SVG feel free to drop a link too.

Thanks for helping!

Upvotes: 1

Views: 1188

Answers (1)

vcapra1
vcapra1

Reputation: 2025

Aligning the text to the center and setting x=0 means that the center of the text will align with the left side of the screen, and half of it will be cut off.

Try this instead:

<text x = "50%" y = "20" id="mainTitle" text-anchor="middle"> Sample Text </text>

Notice that I have used x="50%" and text-anchor="middle". This can be seen as a working example here: https://jsfiddle.net/bov53wz8/4/. Note I also set y="20" to make the title appear closer to the top, but you can change that as you like.

A good tutorial on a site I usually like to go to is: https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial Also, a good reference when using SVG for web design: https://css-tricks.com/using-svg/

Upvotes: 1

Related Questions