How to Vertically and Horizontally Center CSS?

To sustain this free service, we receive affiliate commissions via some of our links. This doesn’t affect rankings. Our review process.

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):

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

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

About The Author:

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.

Disclaimer: This website contains reviews, opinions and information regarding products and services manufactured or provided by third parties. We are not responsible in any way for such products and services, and nothing contained here should be construed as a guarantee of the functionality, utility, safety or reliability of any product or services reviewed or discussed. Please follow the directions provided by the manufacturer or service provider when using any product or service reviewed or discussed on this website.

Notify of
Oldest Most voted
Inline Feedbacks
View all comments

It’s THE method for centering vertically a div in Firefox.

I’ve tried many others that work in Safari, Google Chrome, IE … and not in Firefox.

Thanks for this container “div#center” that do the trick !

I can’t figure out why div both relative and absolute will shift down a little when there is an extra tool bar on my monitor. The background will stay in place but all divs move. Can someone help me out with this? Margins are auto!


.items li
float: left;
margin: 0px 15px 5px 0px;

.items li .outerContainer
display: table;
height: 180px;
overflow: hidden;
width: 200px;
background-color: #EBEBEB;

.items li .outerContainer:Hover
background-color: #4d8dcb;

.items li .outerContainer .innerContainer
display: table-cell;
vertical-align: middle;
width: 100%;
margin: 0 auto;
text-align: center;

.items li .outerContainer .innerContainer .element a
color: #999999;
text-decoration: none;
padding: 0px 10px;
display: block;

.items li .outerContainer:Hover .innerContainer .element a
color: #FFFFFF;
text-decoration: none;

Hi guys,

Centered website with your method and all is good in Firefox and Chrome, but Internet Explorer moves my whole site to the left, so part of it is off-screen. Any ideas?


I’m placing a Google ads link unit next to “Home” and “Contact Admin” in the Top Navigation Bar. The position for the ads unit is not inline with the other text or it is a little bit higher than the other. Can anyone help to resolve this problem?

Here is the code: li a:link, li a:visited { color: #fff; display: block; text-decoration: none; padding: 6px 10px; border-right: 1px solid #E68C87; }

Try taking a little padding off the top (or more to the bottom, depending on how relatively positioned your div is). Or give your ad unit a separate div and adjust the padding for it individually, so your other menu items are not affected.

If you’re getting scroll bars, make sure your body margins and padding are set to zero!

body {

And you don’t have to know the size of your container! #one { text-align:center; margin:0px auto; width:100%; } #two { margin:0px auto; }


I recently found this code which might prove useful… and works for me on Firefox 2 and IE 6 on a PC and Firefox 1.5 and Safari 2 on a Mac.

<style type="text/css">

/* <![CDATA[ */

html, body {

height: 100%; /* Make sure the document takes up the whole window. */

margin: 0; /* Get rid of any default margins, which could cause the html and body elements to be larger than the window and trigger scrollbars. */

padding: 0; /* Get rid of any default padding, which could cause the html and body elements to be larger than the window and trigger scrollbars. */


div#shim {

visibility: hidden;

width: 100%;

height: 50%; /* Bump div#blueBox down half the height of the screen. */

margin-top: -200px; /* Half the height of div#blueBox. */

float: left;


div#blueBox {

background: blue;

width: 100px;

height: 400px;

clear: both;



* Issue: IE4 doesn't allow a negative margin-top.


* This code positions blueBox relatively and uses the IE4ever hack (<>) to overwrite the rule for other browsers.

* The content will be centered but will crop if the window is not small enough to accommodate it.



position: relative;

top: -200px;

/* IE4ever Hack: Hide from IE4 **/

position: static;

/** end hack */




* Issue: IE5mac interprets negative values as positive.


* I haven't figured out a workaround for this yet. The content won't be vertically centered but it won't be messed up by the previous code either.



/* Hide from IE5mac \*//*/

div#shim {

display: none;


html, body {

height: auto;


/* end hack */

/* ]]> */




<div id="shim"></div>

<div id="blueBox">this box should be vertically centered in your browser window</div>


Thanks for the sample. Your example is not centering, however, on Firefox 3.5.5+

The horizontal centering example URL. been there since when????

Are you asking how long the above link has been online? I have no idea. There’s many articles on horizontal centering out there, with many different techniques. The link you mention simply addresses auto-width margins. Our example addresses horizontal and vertical centering.

Your horizontal centering works as I’ve used it before, but a much more simple way is doing the following in your style sheet:


/* align the page and set the width */
body { text-align: center; width: 100%; }

/* set a width, set margins, re-align text to left, set a background to see results more clearly */
.content { width: 200px; margin-left: auto; margin-right: auto; text-align: left; background-color: #006666; }

I’m unable to test this on Mac, but it works in FF, IE6+ on Windows.

Hi, Tried the solution which was great for IE and Firefox on my PC and Safari and Firefox on my Mac, but NOT the now discontinued IE for the Mac. I know IE for Mac is not now supported but is there are way to get around this for the few people left that might still be using it? Interestingly the site example you mentione at does not display at all on IE for Mac – a complete grey screen. Maybe I shouldn’t worry about supporting the old browsers? C

Hi there,

It’s important to support older browsers to an extent. That extend should be determined by how many people still use the browser and how much time you have to invest in browser compatibility vs. the additional number of people you’ll serve with that time. IE 5.2 for Mac is used by a negligible (< 0.5%) of users overall and therefore we did not invest additional time in optimizing for this browser.

IE for the Mac, was incidentally, a very poorly designed browser, and is part of the reason that Mac switched to Safari for OS X (an excellent, ACID (browser standards testing) compliant browser).

Cheers 🙂

No problem 🙂

Actually I appreciate the rant – it always helps to bring CSS discussions into the open to entice interest for anyone that has similar concerns.

I’m totally swamped with work at the moment but will give the example a crack when I have a minute.

Thanks for the feedback and sorry about the rant. If you get time, could you refine your example in the ways that you suggested and see if its possible to get something that works on all resolutions. It would really help me appreciate css.

I see what you’re saying with the top content getting cut off. The key is having your height less than or equal to 600. You can probably also add in extra margin at top and bottom to prevent this from happening – or specify an additional container to control the height.

I felt the same way you do about tables initially, but over the years I’ve learned to really appreciate CSS. The flexibility in positioning it allows is unparalleled, and the degree of control it warrants by allowing control over dozens or hundreds of pages is a huge time saver. It takes a while to get used to, and one of the big hurdles has always been compatibility differences between browsers.

That being said, tables are not completely dead – I still use them to organize tabular data at times. Actually, I also use them in some templates to position content first and menus last – used to be a bigger deal when search engines placed more priority on content at top.

CSS is also a stepping stone. Once the DOM and semantic languages become more prominent (such as XML and XSLT) our control over layout and the integration of data will be way more efficient than it is now.

Thanks for your example but allas it seems to fall down the way all css vertical centering examples do. If you switch to 800×600 you lose a load of pixels from the top of your content and you cannot even scroll up to it, it is just lost.
And the more toolbars you have the worse this problem gets, on ie and firefox, god knows what safari does.
I never had these headaches in html because tables handled it easily and its a constant pain that moving to css means i have to explain to clients why i can’t do something that was easy 10 years ago?
I am constantly amazed at how restrictive css is, is this really the future, someone show me the light. Preferably one that is still visible in all resolutions.

Hi all,

I’ve just been reading this thread. I am a creative designer with over ten years experience in designing for print and some new media, mainly ‘front end creative’. I have decided to learn to hand code using pure html and css. I already had an understanding of html and had to grasp the theory of how it works with css and how the hell elements are positioned using css instead of tables.

I totally agree that using tables was a lot easier, you never had these issues regarding centered content appearing centered in some browsers and not others. I really cannot understand these people that keep saying ‘Oh once you understand how to use css it’s like a breath of fresh air and you’ll never look back’. What a load of bull***!

I too pose the question…is this REALLY the future of web design??? If css and pure mark-up is the future of layout for web pages then God help us! And therefore isn’t it about time the W3C stop P***ing around telling designers and web developers that they have to adhere to their standards, and advising that web pages should be built using pure code in order to obtain ‘their’ stamp of approval? Shouldn’t they actually concentrate their efforts in producing a set of standards for companies creating web browsers so that their code for reading html and css runs in accordance with each other? Surely if the end readers (the browsers) are having problems displaying what is in essence the same html and css coding then there lies the problem. It shouldn’t be up to the designers or coders to mess around looking for hacks and different ways to fool the browsers in order to get their designs to work.

Here’s an analogy:

Imagine you’ve designed a product…let’s say a wardrobe. You want to employ one person to build the wardrobe so that you can sell the product and make some money. You produce all the instructions for building the product and you give exactly the same instructions to four different people in order for them to put the wardrobe together.

Now, two of those people just can’t put the product together in the correct manner. No matter how hard they try they just can’t do it. So what do you do?

a.Waste time and money fiddling around changing the instructions here and there so that those two people can understand them and manage to eventually build the wardrobe?

b.Say thanks but no thanks and eliminate the pair from your choice.

D’you see what I’m getting at? Why the hell should we as designers and programmers waste our time and money (because time is money) fiddling around with snippets of code in order for one or another web browser to display our designs correctly.

There should be one universal web browser. The governments of this world should pour an amount of money into the development of a universal code reading program. Pay the right people and get the job done. Microsoft, Mozilla, and the likes should pool their collective resources and perform this task. Set up one company and therefore one browser. All they would need to do is charge people a minimum amount to download the browser software therefore regaining any funds outlaid in the development process.

Because all designers and coders yearn for this to happen, the ball would start rolling with that demographic until eventually 90% of the world’s population are using this one browser. And ‘hey presto!’ all of a sudden this crazy problem of inter browser compatibility is eliminated!

Just a thought…AHEM,(Microsoft, Mozilla etc), AHEM, AHEM!

Sorry got a bad cough.



Generally the width of my sites are known quantities, but the height of my site may not be. Any idea how you might expand this technique so that you wouldn’t have to know the height before hand? (Or even the width before hand?)

Very nice site, by the way. The look is very inspiring. 🙂

Specifying height for the content element helps you achieve the same space at bottom and top. The first page is centered equally, but other pages the content extends down. The height gives you a starting position. As for the exact amounts – you don’t necessarily need to use pixels. You could use em’s, percentages, or whatever your preferred unit is. Important is that the Content element is positioned 50% from the left, with a negative left margin half its width. This accomplishes the horizontal centering. For vertical centering, it needs to have a negative top position that is half its height. Hope this helps! 🙂