Can overflow text be centered?

Nathan Ryan picture Nathan Ryan · Jul 8, 2011 · Viewed 27.2k times · Source

When I specify text-align:center for an element with a width that is greater than the width of the text, the text is centered within the content box of the element (as expected).

When I specify text-align:center for an element with a width that is less than the width of the text, the text is aligned to the left edge of the content box and overflows the right edge of the content box.

You can see the two cases in action here.

Can any CSS magic make the text equally overflow both the left edge and the right edge of the content box, so that it stays centered?

Answer

Nemo64 picture Nemo64 · Jan 30, 2015

I know this question is old, but I just had the same Problem and found a much easier solution with just a span. http://jsfiddle.net/7hy3w2jj/

<div>some text</div>
<div>
    <span class="text-overflow-center">some text that will overflow</span>
</div>

Then you just need this definition

.text-overflow-center {
    margin-left: -100%;
    margin-right: -100%;
    text-align: center;
}

If you can work with pseudo elements, it can be done with no html at all. Just add these definition to your text container. http://jsfiddle.net/7287L9a8/

div:before {
    content: "";
    margin-left: -100%;
}
div:after {
    content: "";
    margin-right: -100%;
}

The only downside to the pseudo variant is that it only works with one line of text.