Search code examples
csscontainerscenter

CSS container won't center


I started writing my first website, and tried to center the container id in CSS using various methods found on the web (the most common of which being margin-left:auto; margin-right:auto;) but it simply won't work, and I have no idea why, or what could I do about it (I know, I could make a table with three columns in the html file, but I don't want to mix and match tables and divs)

My code so far looks like this:

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>

<body>

<div id="content">
hello world!
</div>

</body>
</html>

CSS:

@charset "utf-8";
/* CSS Document */

body {
background-color:#FFF; 
}

#content {
width:980px;
background-color:#FCC;
position: absolute;
display:block;
margin-left: auto; 
margin-right: auto;
top: 0px;
bottom:0px;
align:center;
}

Solution

  • Solution #1:

    Replace position: absolute; with position: relative; in #content(CSS).

    JSFiddle - DEMO and Full Screen View

    body, html {
        background-color:#FFF;
        height:100%;
    }
    #content {
        width:980px;
        height: 100%;
        background-color:#FCC;
        position: relative;
        display: block;
        margin-left: auto;
        margin-right: auto;
        top: 0px;
        bottom:0px;
        text-align:center;
    }
    <div id="content">hello world!</div>

    More Info about margin: 0 auto; center to work:

    What, exactly, is needed for margin: 0 auto; to work?

    Solution #2:

    Add left: 50%; and margin-left: -490px; (half width of #content div) to #content

    JSFiddle - DEMO and Full Screen View

    #content {
        width: 980px;
        background-color: #FCC;
        position: absolute;
        display: block;
        top: 0px;
        bottom: 0px;
        margin-left: -490px;
        left: 50%;
        text-align: center;
    }