简体   繁体   中英

center a html div (margin 0 auto help)

I am trying to center a footer menu but it is not positioning correctly. I have tried a margin auto 0 which is working for the main container div, but doesn't work on the footer. Please help. Thanks in advance.

html code

<!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>
<link href="css.css" rel="stylesheet" type="text/css"/>
</head>

    <body>
        <div id="container">
            <p>stuff</p>
        </div>

        <div id="footer">
            <ul>
                <li><a href="">link</a></li>
                <li><a href="">link</a></li>
                <li><a href="">link</a></li>
                <li><a href="">link</a></li>
                <li><a href="">link</a></li>
            </ul>
        </div>

    </body>
</html>

css code

body {
    font-family: Arial;
    padding-bottom: 50px;
}

a, a:link, a:visited, a:active {
    text-decoration: none;
}

#container {
height: 300px;
width: 500px;
margin: 0 auto;
padding-bottom: 10px;
border: 5px solid #dbdbda;
}

/*footer*/
/*
#footer {
margin: 0 auto;
}
*/
#footer ul {
font-size: 10px;
list-style: none;
}

#footer li {
float: left;
}

#footer li a {
padding-left: 10px;
padding-right: 10px;
border-right: 1px solid #dbdbdb;
color: #323232;
}

#footer li a:hover {
color: #dbdbdb;
}

margin: 0 auto无法在没有width情况下工作,尝试设置fixed width ,例如width: 100px;

You can give display:inline-block to ul tag inside your footer and text-align:center to footer.

This will help to be independent from number of li's in footer. Otherwise, you must give width to your footer, which isn't correct in this situation, because you can need to add some element to footer and changing width everytime isn't nice solution.

See updated jsfiddle

Give your footer a fixed width, or it won't know what "center" actually means in relation to the rest of the page.

#footer {
    width:500px;
    margin:auto;
}

Use this css,

#footer {
text-align:center;
}
#footer ul {
font-size: 10px;
list-style: none;
display:inline-block;
width:500px;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM