How to Vertically and Horizontally Center CSS?

How do we keep this site running? This post may contain affiliate links — the cost is the same to you, but we get a referral fee. Compensation does not affect rankings. Thanks!

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 bring a series of in-depth articles on search marketing and content management systems as well as troubleshooting tips to We Rock Your Web's collection. He is an avid tennis player, nature enthusiast, and hiker, and enjoys spending time with his wife, friends, and dogs, Bella and Lily.

Leave a Reply

22 Comments on "How to Vertically and Horizontally Center CSS?"

avatar
Anonymous
Anonymous

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:

ul.menu li a:link,ul.menu li a:visited { color: #fff; display: block; text-decoration: none; padding: 6px 10px; border-right: 1px solid #E68C87; }

We Rock Your Web
We Rock Your Web

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.

Anonymous
Anonymous

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 (<http://exanimo.com/css/ie4ever>) 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 */

/* ]]> */

</style>

</head>

<body>

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

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

</body>

We Rock Your Web
We Rock Your Web

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

Anonymous
Anonymous

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.

Anonymous
Anonymous

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.

Marc

Flho
Flho

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 !

suzanne
suzanne

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!

Anonymous
Anonymous

CSS:

.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;
}

Anonymous
Anonymous

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?

Cheers!

Anonymous
Anonymous

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

body {
margin:0;
padding:0;
}

Anonymous
Anonymous

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; }

Anonymous
Anonymous

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

Anonymous
Anonymous

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

CSS:

/* 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.

Anonymous
Anonymous

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 http://www.endust.com/ does not display at all on IE for Mac – a complete grey screen. Maybe I shouldn’t worry about supporting the old browsers? C

Anonymous
Anonymous

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.

Anonymous
Anonymous

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.

wpDiscuz

Send this to a friend