我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。
当前回答
将这个类添加到你想居中的div(它应该有一个设置的宽度):
.marginAutoLR
{
margin-right:auto;
margin-left:auto;
}
或者,添加边缘到你的div类,像这样:
.divClass
{
width:300px;
margin-right:auto;
margin-left:auto;
}
其他回答
body, html {
display: table;
height: 100%;
width: 100%;
}
.container {
display: table-cell;
vertical-align: middle;
}
.container .box {
width: 100px;
height: 100px;
background: red;
margin: 0 auto;
}
http://jsfiddle.net/NPV2E/
“body”标签的“width:100%”仅为示例。在实际项目中,您可以删除此属性。
只需在body标签之后使用center标签,并在body结束之前结束center标签:
<body>
<center>
... Your code here ...
</center>
</body>
在我尝试过的所有浏览器中,这都是可行的。
<body>
<div style=" display: table; margin: 250 auto;">
In center
</div>
</body>
如果你想改变垂直位置,改变250的值,你可以根据你的需要安排内容。不需要给出宽度和其他参数。
旧代码中其他一些预先存在的设置将阻止div页面居中L&R:
隐藏在外部样式表链接中的其他类。 其他类嵌入到像img这样的东西中(比如旧的外部CSS打印格式控件)。 带有id和/或CLASSES的图例代码将与命名div类冲突。
<div></div>
div {
display: table;
margin-right: auto;
margin-left: auto;
}