Centering Text Inside a Container


Categories
Tags
In this quick tutorial, learn how to center text both horizontally and vertically with just a little CSS.

This is a simple, yet very effective technique, that allows you to center text both vertically and horizontal within a containing div. This could be used to overlay text on banner images, menu boxes etc, adding a nice visual element to your website(s) or web app(s).

Centring the text horizontally is really straightforward, simple text-alignment covers that. To center it vertically we use the position property. Note that two position elements are needed; relative positioning for the outer container, and absolute positioning for the inner container.

Here’s a very simple example of what we want to achieve:

Some Text

And here’s the code that does it:

<div style="position:relative;">
	<div style="height:150px;border:1px solid red;padding:2em;">
		<div style="text-align:center;position:absolute;top:0;left:0;right:0;top:50%;transform:translateY(-50%);margin:0 2em;">
			Some Text
		</div>
	</div>
</div>

For divs that have a variable height, you could also achieve this with:

position:relative;top:50%;transform:translateY(-50%);

Comments

Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.

Disclaimer and Legal Information

The use of any content found on or via this website (code, how to guides etc.) is done so at your own risk. We take no responsibility for any issues encountered.

This blog and its authors will not be held responsible for any misuse, reuse, recycled and cited/uncited copies of content from this website by others.

The views and opinions expressed in this blog are those of the author(s) and do not necessarily reflect the position or opinion of any other agency, organisation, employer or company.

Comments are moderated but we do not take any responsibility for any libel or litigation that results from something written in a comment. We reserve the right to reject or delete any comment for any reason whatsoever (abusive, profane, rude etc). Please keep your comments polite and relevant.

We are happy for you to quote and share our content in any reasonable manner, e.g. post links to our blogs on social media, but not in any way that suggests that we, or our authors, endorse you, your use or your views. Nothing negative please.

We appreciate attributions, e.g. a link to our website (www.dragoncode.co.uk).

Thank you – we hope you find the website useful.