Center div in page

对着背影说爱祢 提交于 2019-12-10 11:56:29

问题


I know this has been asked a thousand (million?) times, but for the life of me I can't figure out why I can't get a div to center on my page. Even with the HTML and CSS stripped down to the bare minimum.

I'd appreciate it if someone could point out what I'm missing here.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

<html>
    <head>
        <style type="text/css">
            div#branchSelect { margin: 0 auto; }
        </style>
    </head>
    <body>
        <div id="branchSelect">
            <h4 class="selectBranch">Select a Branch to View</h4>
            <select type="select" id="ddlBranches" class="selectBranch">
                <option id="defaultBranchesListItem" value="0">Select a branch...</option>
                <option value="1">Atlanta</option>
            </select>
        </div>
    </body>
</html>

Here's a jsFiddle.


回答1:


divs are automatically set to 100% width.

Just set the width of the div and use the margin: 0 auto; to center it on the page.

div#branchSelect {
    width:300px;
    margin:0 auto;
}



回答2:


Your div lacks a width property and so by default its with is 100%, so no matter what you do it gets streatched all the way accross the screen, so just assing a width property to your div and then set the margin as "0 auto" in style as shown by Marcus Recck

<body>
    <div style="width:800px; margin:0 auto;">
        centered content
    </div>
</body>


来源:https://stackoverflow.com/questions/14523037/center-div-in-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!