How to Center a Website With CSS

Centering a website is a key part of many CSS layouts. While there are many ways to do it in a variety of situations, the following is an explanation that is purely CSS, avoids messing with percentages, and is compatible with all modern browsers.

I’ve gotten in the habit of starting by resetting any default margins or padding set the browser. Browsers have default style sheets that are loaded automatically as a foundation for any other CSS. Firefox, for example has a default body margin of 8px. This is a simple way to reset any default values that could interfere with the CSS we are trying to write.

More extensive “reset” stylesheets are available, but for the purpose of this exercise we will only reset the essentials, and keep the code to a minimum.

I will be using a main div tag with an ID of “wrapper” for this tutorial. You can set the width to any value your site needs (keep resolutions in mind!) I have picked a width of 960px in favor of a higher resolution average (1024×768). The basic page structure is broken down below:

Centered page breakdown

We are first going to assign a style for the #wrapper div tag that will center it within the browser. This is done using the margin parameter. Remember to specify the width of the #wrapper or the element will not center. After all, it’s hard to center something that takes up 100% of width available. For testing purposes you may want to assign a background color and height to the #wrapper to see the results.

Put simply, Internet Explorer has some issues. When all the other browsers are told to jump, Internet Explorer reinvents the term jump and then hits the deck. One of the joys of web design is compensating for these differences in interpretation. In this case, Internet Explorer 6 will need some special attention center the main div (#wrapper).

In order to compensate for IE6′s shortcomings we have to first set the text alignment to center. This will ensure that the wrapper gets centered on the page.

The body tag encapsulates the wrapper, so the text alignment on it is inherited by the wrapper. Odds are you will want the text to be left-aligned. To do this we will need to  update the #wrapper styles to set the alignment back to the left.

That should do it! This small block of CSS can center any website needed, simply change the sizes. Your complete CSS code should resemble the block below:

Posted Monday, November 24th, 2008 · Back to Top

SPONSOR

Add Comment

96 Comments 8 Mentions

  1. Dustin Author Editor

    Very simple and easy :). Straight forward and to the point tutorial that is easy to follow and has a touch of originality. I like it, bookmarked.

    ·

  2. Matt Author Editor

    There’s a better method, but what you have is great as well. Instead of using text-align:center; which will center all elements in the body tag, use margin-left:auto; and margin-right:auto; . Using text-align:center will center all text and makes you override it in each div, or the main div, like you did in the #wrapper. You won’t need to using the margin-left and margin-right.

    But thanks for taking the time to submit a great tutorial for those who don’t know CSS very well, :).

    ·

    • Amitabh Author Editor

      Thanks a lot.

      ·

  3. Brian Author Editor

    @Matt – Isn’t “margin:0 auto;” the same thing as “margin-left:auto; and margin-right:auto;” ?

    ·

  4. Matt Author Editor

    Yeah, ^_^. It’s just a coding preference, I don’t like combining much of the rules ’cause I feel that individual rules for each side gives more control, for instance, with differing colored borders on each side to give a 3d-ish appearance (although I don’t, it’s just an example). Sorry for a late response, been a bit busy at work creatin’ a customer service course.

    ·

  5. Matt Author Editor

    Lol, mixed two different posts with a copy/paste, sorry. Scrap that borders part. I”ve heard some people have problems in IE using margin:0 auto;, so I also do it just to avoid any potential issues in that department in case they ever did arise, for whatever reason. But yes, it’s the same.

    ·

  6. Siiri Author Editor

    Thank you so much!!! I’ve been trying to do this for about 2 weeks with no results. Every other instruction I managed to find didn’t work. But with your help here I finally was able to fix my problem. Very simple.. thanks :)

    ·

  7. Jarrid Author Editor

    Rather than using text-align:center; use the following
    #wrapper{
    width:960px;
    margin:0 auto 0 auto;
    }
    Now you do not have to use the text-align:center; on the body to make it work in IE6.

    ·

    • Zach Dunn Author Editor

      @Jarrid

      I’m a little confused with the difference of your solution from the one listed in this tutorial.

      Margin:0 auto; is shorthand for exactly what you have written. The text-align changes have to occur in order to prevent IE6 from rendering incorrectly. The option laid out above will center a website, and do so in all browsers. It really can’t be cut down any more — everything listed is needed.

      ·

      • Susan Author Editor

        Thanks Zach! What you described above works great but you can’t take any shortcuts. In order for things to display the between IE and Firefox, these things have to be done or it’s NOT centered. My text is still left aligned inside the divs because that’s how I need them. THANKS a bunch!!

        ·

  8. пpивидeниe Author Editor

    Хм… что-то у меня ссылка не открывается, которую указали. Это у всех так, или только у меня?

    ·

  9. Lieur Author Editor

    Lieuy euy, kurang ngerti
    tapi gpp, walu bgaimana pun
    tutorialx bagus banget

    OK dech,, Thanks a lot for u’r Tutorial^^

    ·

  10. New Author Editor

    Hi there, I am just learning CSS. Can you please tell me how to do the side colors.

    ·

  11. Raz Author Editor

    Actually I too would like to know how you would add a little color or design to the left and right sides of the now centered website! White sides can be a little boring… Besides having a solid color is it easy to implement a repeating background image on the sides like a logo?

    Thanks!

    ·

    • Sam Dunn Author Editor

      @Raz
      It’s simply a matter of adding something like “background-color: #000000;” to the style of the body

      ·

  12. awk Author Editor

    Hi,
    I have tried this all morning but seem to be getting nowhere!
    Can I paste my css somwhere so someone may be able to point out my problem?

    Thanks

    ·

  13. Matt Author Editor

    Thank you so much!!! I have been trying to do this for hours to no avail and then I found your wonderful website! Your explanation was so simple an easy!

    ·

  14. Phil Davies Author Editor

    Thanks for a great tutorial helps lot

    ·

  15. Pavitra Author Editor

    What about centering it vertically …?

    ·

  16. local Author Editor

    what about center tag?

    ·

  17. Dannielle Author Editor

    I know NOTHING about css. But I am trying to learn. This code seems simple, but I don’t know where to put the css code. I tried creating a new css and putting it there but did not work. Can someone tell me exactly where to put this css code in my site. Also, do I need to do it for every page? I have over 20 pages! Thanks

    ·

    • stijn Author Editor

      every page should contain a linking line in the head

      ·

  18. Mike Behnken Author Editor

    Hello, I desperately need to center my site and make the background black… my CSS sucks so I cannot figure out how to do it… If someone has an easy solution, please contact me

    ·

  19. Eswar Author Editor

    Good ways
    simple way to set center margin:0px auto;

    some times center tag can also do center

    Here are another ways to center http://www.templatespoint.com/blog/2009/06/how-to-center-main-div/

    ·

  20. Montreal Web Design Author Editor

    I would recommend to try Compass Style (compass-style.org), it is a CSS generator/framework that makes it easy to create CSS for a website.

    ·

  21. Brenna Ahern Author Editor

    This article just saved my sanity! Thank you!!

    ·

  22. jadox Author Editor

    Hi all,
    The web page I designed works perfectly in firefox, but is all messed up in IE, where the content shoots to the right and the link don’t work. From my research I think the problem is something to do with the doc type but I still haven’t been able to fix it. I don’t think the problem is my css.
    http://www.pipersquickspan.com.au

    body {
    margin:0 auto;
    text-align:center;
    }
    #container {
    margin-left:auto;
    margin-right:auto;
    text-align:center;
    width: 985px;
    display:block;
    position:relative;
    }

    ·

  23. Janet Author Editor

    This didn’t work for me :( Only my top banner centered, nothing else. Any advice?

    ·

  24. tuttifrutti Author Editor

    @janet

    you need to use a main div tag in order to center a page. in this tutorial #wrapper is the main div

    ·

  25. Oliste Author Editor

    Something important when we try to center a webpage is to set POSITION:RELATIVE;, inside the wrapper.

    #wrapper{
    width:960px;
    margin:0 auto;
    text-align:left;
    position:relative;
    }

    DON’T FORGET IT!!

    ·

    • Lew Author Editor

      Something important when we try to center a webpage is to set POSITION:RELATIVE;, inside the wrapper.

      #wrapper{
      width:960px;
      margin:0 auto;
      text-align:left;
      position:relative;
      }

      DON’T FORGET IT!!

      Why do all these tutorials leave that part out? Could’ve saved hours of pulling out my hair. :P Thank you, Oliste. I did forget that part.

      ·

  26. Mzenene Author Editor

    Thanks man, worked like a charm, i was close to quitting.

    ·

  27. NameCo Author Editor

    very good products, just to say to my friends.

    ·

  28. web tasarım izmir Author Editor

    nice review ,and awesome article thanks for the post, I found this blog just yet but I am adding you to my bookmarks

    ·

  29. HurdanStore Author Editor

    Mmmm my website works fine with firefox, but in IE it’s completely mess, please tell what should i do now, i need my body content in to be centered. One more thing is that my body is stretching in big screens and getting small in small screens horizontally. Just try my website in Firefox and in IE and you’ll notice. Does someone know how to align wy website body in centre and stop stretching? lol gosh replies asap

    ·

  30. HurdanStore Author Editor

    My website is: hurdanstore. com

    ·

    • Fraserburgh SEO Author Editor

      I wonder if you gave up on your website or just moved to the new domain as there is no website on the address you provide…

      ·

  31. Alexander Roche Author Editor

    Thanks for this!!!!!!

    ·

  32. Lii Author Editor

    nice tut bro

    ·

  33. Akshay Author Editor

    margin: auto; working fine for me .. !

    ·

  34. kleet81 Author Editor

    Hi The best advise. It helped with my design. I have added you guys to my top website advise folders bookmark.
    Thank you and
    God Bless

    ·

  35. Nik Author Editor

    THANK YOUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU SOOOOOOOOOOOOO MUCHHHHHHHHHHHHHH

    ·

  36. Madhu Kaleeckal Author Editor

    How we can avoid this unlimited resource..

    Thanks

    ·

  37. Kim Author Editor

    This is my first website…..I cannot seem to get my website centered on internet explorer, it is perfect on firefox, I have read all the suggestions above but do not know where to start, ie which file do I make these amendment to, please help

    Thanks Kim

    ·

  38. manish Author Editor

    user
    body{text-align:center;}
    #wapper{width:960px; margin:0 auto; text-align:left;}

    ·

  39. silas Author Editor

    very useful . Thanks for the post

    ·

  40. David Author Editor

    Thanks a lot….

    It saved hours of my time…

    at the end of my frustration, i found this… thank you very very mcuh

    ·

  41. Mark Author Editor

    Very well done indeed. Easy to follow and it works – wow

    ·

  42. Jen Author Editor

    Extremely helpful. All of my IE shenanigans have been resolved.

    ·

  43. Corby Author Editor

    Can you post the HTML markup also?

    ·

  44. Kristopher Author Editor

    Hi peeps.

    I’ve got a site in progress. I have created other sites and can get these to centre/center perfectly fine in all browsers.
    Am however with my most latest coded website unable to get it to centre/center. I’ve damn near re-writtent the structure and yet must be missing something simple.

    site gubbins… A mixture of relatives and absolutes… All absolutes positioned within a relative container.

    #site-wrapper {position: relative; min-width: 1280px; margin: 0 auto;}

    Site in progress can be found @ itechsavvy.co.uk

    A fresh pair of eyes needed I think!! Thank.

    ·

    • Kristopher Author Editor

      Ureka!!
      I tested all div’s by placing a 1px solid red border (div {border: 1px solid red;}) so that that I could see what was hindering the site from centering The child containers (Nested divs) had been inheriting the width of the #site-wrapper (parent), therefore a min-width: 1280px.

      Fix. -Applying a fixed with to the main (parent) container:
      #site-wrapper {position: relative; margin: 0 auto 0; width: 832px;}

      ·

  45. Reverse Phone Lookup Author Editor

    Hello There. I found your blog using msn. This is an extremely well written article. I’ll make sure to bookmark it and come back to read more of How to Center a Website With CSS | Build Internet . Thanks for the post. I will definitely comeback.

    ·

  46. Best Android widgets Author Editor

    How to Center a Website With CSS | Build Internet I was suggested this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my trouble. You’re wonderful! Thanks! your article about How to Center a Website With CSS | Build InternetBest Regards Cassetta

    ·

  47. Eii Su (@eiisuDluffy) Author Editor

    Thank you so much. It is a very helpful tutorial. =)

    ·

  48. Tanya Author Editor

    THANK YOU! Been researching this for quite a while. I found many different answers. This is the only one that worked properly with the other CSS codes on the site I was working on. Was able to modify this to wrap around several different DIV tags. Again, THANK YOU!

    ·

  49. Urud Poetry Author Editor

    Its relay help me to Center a Website With CSS.. Thanks a lot Mr. Zach Dunn for helping us…

    ·

  50. Alex Author Editor

    As far as my testing goes, unless I’m not doing something right, this won’t cut it in sites with absolute positioning for elements. Shame, because I was just hoping it might solve my aesthetic issue on http://www.lunchbrakes.com – some people like to have a centred site when they have bigger screens. As everything is absolute positioning, this css trick just doesn’t work! :(
    Will be very useful for other sites though, thanks.

    ·

    • Kristopher Rout Author Editor

      Hi Alex, the trick I’ve found is to use a relative positioned parent element as a reference for absolutely positioned elements. -When the screen is a different size and the margin: 0 auto elements shift to the center of the screen, the absolute elements shift as the absolutely positioned items are anchored to the parent element… for example:

      css:
      #site-wrapper { width: 1280px; margin: 0 auto; } /* ~~ This deals with the centering ~~ */
      #relative-parent { position: relative; width: 100% **(1280px)**; } /* ~~ Anchor element ~~ */
      #absolute-child { position: absolute; top: 0; margin-top: **Offset Top**; left: 0; margin-left: **Offset Left**; bottom: auto; right: auto; height: **Object Height**; width: **Object Width**; } /* ~~ Item to be positioned ~~*/

      html:



      The anchor is achieved through the use of the the top: 0; & left: 0;. -It binds the absolute to the parent relative container (Div in the example). In order to position the absolute you can use margin-top & margin-left. *** Equally bottom and right can be used with the opposite margin’s… BUT keep all absolutely positioned elements using this method the same (Top & Left, Top & Right, Bottom & Left, Bottom & Right) using different selectors will cause inconsistency in most cases!

      Is working amazingly well for my website… I also intend to use a lil script to accommodate larger screens with larger images and containers, however the use of code above remains the same with only a few tweaks with the margin-left for the absolute elements.

      Hope this helps!!

      ·

      • Kristopher Rout Author Editor

        It’s hidden the html! lol.

        div id “site-wrapper”
        div id “relative-parent”
        div id “absolute-child”
        /div (absolute-child)
        /div (relative-parent)
        /div (site-wrapper)

        Hopefully this comes out. :o)

        ·

  51. Adam Morgan Author Editor

    Nice and simple piece of advice here, good work!

    ·

  52. Trupti Author Editor

    Thanks, this was very helpful.

    ·

  53. nagul Author Editor

    how to fix the wrapper height centered in all the screen.

    ·

  54. Jamie Pearce Author Editor

    Hey

    Why wont my div centre? Please can you help =D

    #Mainfill {
    width: 1480px;
    height:1500px;
    margin:auto;
    text-align:left;

    ·

    • Eoin H Author Editor

      Try using

      margin: 0 auto;

      Hope that helps.

      ·

  55. Eoin H Author Editor

    Thanks for the tut, been popping on here for ages but never got round to posting a quick thanks.. I actually use the above css as standard now (with the position:relitive;) as part of my main stylesheet template when starting a new design project.

    So, even tho its just a small snippet of code, its made a big impact on my work over the last few years. so big thanks for that.

    ·

  56. mommahen Author Editor

    I am so confused. Apparently, the only html I can learn is how to screw it up. My site is all out of whack.

    ·

    • Computer Guy Author Editor

      But your website looks all good.Did you learn a few tricks since your comment? …and than I’ve spotted your “tomato rubbed garlic toast with a poached egg”. You made me hungry at 3 in the morning, that’s what is wrong with your website :)

      ·

  57. Balaji Author Editor

    Please help me how to set default one css in website becoz i am using multi style sheet…!!

    ·

    • Charity Author Editor

      I think your problem lies somewhere in the land of English grammary. Ever thought that improving your English could also help you with coding?

      ·

  58. Nails Malaga Author Editor

    I have to redo my website as I have used the free template provided by my previous hosting. Now – I wonder whether it’s better to start everything from the scratch or use some wordpress template. My website has over 20 sites and quite a lot of pictures, some nails videos etc.

    ·

    • Animal Sanctuary Author Editor

      I think it would be beneficial to change our website as well. How do you apply wordpress theme to your website? Do you have to install something on the server? We only know how to work with cPanel.

      ·

    • Kasia Author Editor

      It’s actually pretty easy to do the website from the scratch if you have good resources (code, scripts etc). I am putting my website all together at the very moment and I’m none of the web designer :) It just requires resources, time and patience :)

      ·

    • Zumba Author Editor

      Hi Jagoda. I just visited your new website, it looks astonishing indeed. Can’t wait to see it in full glory :)

      ·

  59. HAMED Author Editor

    ok…tanx a lot
    that’s great mr Zach Dunn.
    :)

    ·

  60. Josh Author Editor

    Thanks.

    ·

  61. Yeli Design Author Editor

    great job . Thank you very much.

    ·

  62. Iphone Oyunlari Author Editor

    great article .Do you have any post about css sprite ? or combine a lot of css into one css file ? Thanks.

    ·

  63. Mukoro Godwin Author Editor

    So simple and saved time of redoing my website the third time to make work in ie. I thought of going on without solving the ie problem if those at ie don’t bother. But thanks to you.

    One more my min height and max height dont work in ie any solution please

    ·

  64. Joshua Author Editor

    Worked like a charm! Thanks!

    ·

  65. Matt May Author Editor

    Very well explained – the only slight thing I would suggest is adding an example of the use of the wrapper div class in the html for people who are new to css

    ·

  66. Web Design Fraserburgh Author Editor

    Looks like your website is not loading properly.
    Hope its got nothing to do with centering a website with CSS :D

    ·

    • Zumba Peterhead Author Editor

      Works fine for me, maybe you happened to get cached version? It happens sometimes during server update. Otherwise there is something wrong on your side :)

      ·

  67. facebook cover Author Editor

    This is a really good tip particularly to those fresh
    to the blogosphere. Brief but very accurate info… Thank you for sharing this one.
    A must read post!

    ·

  68. Angus Author Editor

    Finally, the tutorial I was looking for….

    Much appreciated!

    ·

  69. Todays Modern Wife Author Editor

    Hi there would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 different web browsers and I
    must say this blog loads a lot quicker then most. Can you recommend a good internet hosting provider at a reasonable price?
    Cheers, I appreciate it!

    ·

  70. Raunchy Wife Author Editor

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment
    is added I get three emails with the same comment.
    Is there any way you can remove my fathers son from
    that service? Appreciate it!

    ·

  71. Apple news Author Editor

    Appreciation to my father who stated to me about this weblog, this web site is really amazing.

    ·

  72. Raspberry Ketone Author Editor

    Your mode of describing the whole thing in this article is truly
    fastidious, all be capable of without difficulty be aware of it,
    Thanks a lot.

    ·

  73. Www.Jerky.Com Author Editor

    Quite aside from the value of consuming out
    as in comparison to eating at dwelling, it is really possibly just not practical to dine in a restaurant every last single day.
    And according to my short research, celery stalk contains PHTHALIDE which can lower blood pressure, and also it lessens the production of catecholamine (exists if physically
    and emotionally stressed) which causes the imbalance
    flow of blood by restricting or blocking the blood vessels.
    6 medium carrots, cut into 2 inch pieces and halved lenghtwise.

    ·

  74. Rodger Author Editor

    adsense_ad_unit += ” +.
    It can be made ahead and kept in the fridge while
    the shredded chicken is being prepared. Beverages, breads, desserts, main courses,
    salads, and dressings – there was a Tupperware recipe for every part of a meal.

    ·

  75. Agatha U. McWilliams Author Editor

    I’m extremely impressed together with your writing talents as well
    as with the format in your blog. Is that
    this a paid theme or did you modify it your self?

    Anyway keep up the nice quality writing, it is rare to peer a
    great blog like this one nowadays..

    ·

  76. Axl Hazarika Hum Badal Gaye Author Editor

    Hi everyone, it’s my first go to see at this site, and article is in
    fact fruitful designed for me, keep up posting such articles or reviews.

    ·

  77. autohaus radolfzell Author Editor

    I just could hardly keep your internet-site just before advising that I in fact adored the usual details somebody source with your friends? Is likely to be just as before regularly as a way to look at fresh posts

    ·

 

Build Internet by One Mighty Roar. Since 2008.