Skip to content

Instantly share code, notes, and snippets.

@LeaVerou
Created March 23, 2013 23:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save LeaVerou/5229803 to your computer and use it in GitHub Desktop.
Save LeaVerou/5229803 to your computer and use it in GitHub Desktop.
Vertically centered text with SVG
/* Vertically centered text with SVG */
div {
width: 300px;
height: 150px;
background: #f06;
font: bold 150% sans-serif;
text-shadow: 0 1px 2px rgba(0,0,0,.5);
overflow: hidden; resize: both; /* just for this demo */
color: white;
}
svg {
width: 100%; height: 100%;
pointer-events: none; /* so that you can resize the element */
}
text {
text-anchor: middle;
pointer-events: auto; /* Cancel the svg’s pointer-events */
fill: currentColor;
}
p {
font: italic 100% Georgia, serif;
}
<p>
Resize the div below from the handle at the bottom right corner (if your browser supports the <code>resize</code> CSS property)
or change the CSS code to observe what happens at different dimensions.
</p>
<div>
<svg><text x="50%" y="50%" dy=".3em">
Look, I’m centered!
</text></svg>
</div>
// alert('Hello world!');
{"view":"split","fontsize":"100","seethrough":"","prefixfree":"1","page":"css"}
@alexeyraspopov
Copy link

Is it better than obvious

display: table-cell;
vertical-align: middle;

?

@danillonunes
Copy link

Make something that is not a table cell behaves like a table cell just for the sake of vertical alignment is anything but obvious.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment