Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to center a webpage's content using css?

Tags:

html

css

I have seen several methods for creating simple fixed width single column layout using CSS. I like the one shown here because there is very little code involved and it works on every browser I have tried.

#container {
  margin: 0 auto;
  width: xxxpx;
  text-align: left;
}
<body>
  <div id="container">
    ...entire layout goes here...
  </div>
</body>

The author mentioned that he received some criticism. I not a web developer so I wanted to ask the community what they thought about this approach. More specifically is there a better/more compatible way to accomplish this?

like image 293
Lawrence Barsanti Avatar asked Jan 07 '10 02:01

Lawrence Barsanti


People also ask

How do I center a contents form in CSS?

To just center the text inside an element, use text-align: center; This text is centered.

How do I center a login form in CSS?

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

How do you center content in a span?

To center an inline element like a link or a span or an img, all you need is text-align: center . For multiple inline elements, the process is similar. It's possible by using text-align: center .


2 Answers

The "margin: 0 auto" is the best way to do it, you just have to be sure to have the right doctype for it to work. I always use XHTML strict - others will work too. If you don't have a good doctype, the content won't center in IE6

To implement the XHTML strict doctype, put this above your node, as the first line in the page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
like image 132
James Maroney Avatar answered Nov 08 '22 17:11

James Maroney


margin: 0 auto; ( or margin-left: auto; margin-right: auto; ) is really the simplest way., and there's really no issue with sticking with it for centering content.

I'm of the opinion that the width tag should be max-width: xxxpx. For those on mobile browsers with a tiny 360px or smaller width, they will simply get the biggest possible size for your container that fits in their screen size (but then your inside layout will have to scale gracefully too.) Also of note is that max-width does not work on IE6.

like image 42
Crast Avatar answered Nov 08 '22 19:11

Crast