Web Development

How to Vertically and Horizontally Center CSS?

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

Alex Schenker

Alex has been involved on the business side of the internet since the early 2000's. He holds both a Management Science degree from the University of California at San Diego as well as a Computer Science degree from NJIT. We Rock Your Web had its roots back in 2004 as the tech blog for a web design and development company Alex founded that has grown and evolved into the parent company of We Rock Your Web. While his foundation is rooted in web development, his expertise today lies in content and digital marketing, SEO, organic and paid search, analytics, and publishing. Alex is an avid tennis player, nature enthusiast, and hiker, and enjoys spending time with his wife, friends, and dogs.

Related Articles

Subscribe
Notify of
22 Comments
Newest
Oldest Most voted
Inline Feedbacks
View all comments
Back to top button
Index