我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。
当前回答
这可以通过flex容器轻松实现。
.container{
width: 100%;
display: flex;
height: 100vh;
justify-content: center;
}
.item{
align-self: center;
}
预览链接
其他回答
如果你的中心内容深在其他div,那么只有边缘可以拯救你。什么都没有。当我不使用Bootstrap这样的框架时,我总是面临这个问题。
你也可以这样使用它:
<div style="width: 60%; margin: 0px auto;">
Your contents here...
</div>
将这个类添加到你想居中的div(它应该有一个设置的宽度):
.marginAutoLR
{
margin-right:auto;
margin-left:auto;
}
或者,添加边缘到你的div类,像这样:
.divClass
{
width:300px;
margin-right:auto;
margin-left:auto;
}
出于某种原因,之前的答案对我都不起作用。这对我来说很管用,而且在不同的浏览器中也同样适用:
.center {
text-align: center;
height: 100%;
/* Safari, Opera, and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Internet Explorer 10 */
display: -ms-flexbox;
-ms-flex-pack: center;
-ms-flex-align: center;
}
为了让它在ie6中也能正常工作,你必须这样做:
HTML
<body>
<div class="centered">
centered content
</div>
</body>
CSS
body {
margin: 0;
padding: 0;
text-align: center; /* !!! */
}
.centered {
margin: 0 auto;
text-align: left;
width: 800px;
}