How to Vertically and Horizontally Center CSS?

When you purchase through links on our site, we may earn a commission. Here’s how it works.

How to Vertically and Horizontally Center a CSS Element?

Pre-css most centering was accomplished using the grid-like structure that tables provided. All fine and good, but the CSS positioning module offers layout options that tables could only dream of. Here’s how to vertically and horizontally center an element in pure CSS.

The Container Element

#center { position: absolute; top: 50%; width: 100%; height: 1px; overflow: visible }

The goal here is to position the container element 50% from the top of the page. It’s important that you specify a height for the container element and that its overflow be set to visible.

The Content Element

#main { position: absolute; left: 50%; width: 720px; margin-left: -360px; height: 540px; top: -270px }

The Content element is nested inside the Container element and is positioned 50% from the left, with a negative left margin half its width. This accomplishes the horizontal centering. For vertical centering, we give the element a negative top position that is half its height.

Note: Whenever you specify position (top:, left:) make sure you first specify position: absolute. While newer browsers will render the page without the position: absolute statement, older browsers may not, your CSS may not validate (or will validate with warnings). Bottom line it is always good practice to specify declarations when in doubt.

Putting it all together

Here’s an example of all the above code combined to horizontally and vertically center a CSS element:

In your HTML File (ie. index.htm):

<html>
<head>
<title>CSS Centering Example</title>
<link rel="stylesheet" type="text/css" media="all" href="styles.css" />
<body>
<div id="center">
<div id="main">
<p>This text is perfectly vertically and horizontally centered.</p>
</div><!-- end #main -->
</div><!-- end #center -->
</body>
</html>

In your CSS File (ie. styles.css):

#center { position: absolute; top: 50%; width: 100%; height: 1px; overflow: visible }
#main { position: absolute; left: 50%; width: 720px; margin-left: -360px; height: 540px; top: -270px

Tagged With:

The information provided through this website should not be used to diagnose or treat a health problem or disease; it is not intended to offer any legal opinion or advice or a substitute for professional safety advice or professional care. Please consult your health care provider, attorney, or product manual for professional advice. Products and services reviewed are provided by third parties; we are not responsible in any way for them, nor do we guarantee their functionality, utility, safety, or reliability. Our content is for educational purposes only.

Subscribe
Notify of
22 Comments
Newest
Oldest Most voted
Inline Feedbacks
View all comments