Jump to content
SSteven

How to center text in an SVG graphic?

Recommended Posts

The following HTML creates an SVG rectangle containing a horizontal linear gradient and text, intended as a Banner.

https://jsfiddle.net/SSteven/z7umqfpw/

Note that the text is not centered.

How do I center the text?

I tried the following, using some information on the web:
  https://stackoverflow.com/questions/41822510/center-an-svg-inside-a-div

However, my attempt doesn't work:

https://jsfiddle.net/SSteven/5jg7xhwu/

Share this post


Link to post
Share on other sites

Go to the first link code and just adjust y position value and add text-anchor="middle"

        <text x="50%" y="60%" fill="white" font-size="45" font-family="Verdana" text-anchor="middle">THE NY TRIBUNE</text>

 

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for this info. It works perfectly for the horizontal centering. However, vertically, it doesn't appear to be centered. Is there any way to center SVG text vertically? There doesn't appear to be an attribute of <text> for this. Is there a way to do it using JS? (eg: to return the height of the text (th) and the height of the banner (bh) and then do (bh - th)/2, for instance?)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×