我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。


当前回答

Flexbox解决方案是2015年的发展方向。Justify-content: center用于父元素将内容对齐到它的中心。

HTML

<div class="container">
  <div class="center">Center</div>
</div>

CSS

.container {
  display: flex;
  justify-content: center;
}

输出

.container { 显示:flex; justify-content:中心; } .center { 宽度:400 px; 填充:10 px; 背景:# 5 f85db; 颜色:# fff; 粗细:大胆的; 字体类型:大河马字体; } < div class = "容器" > <div class="center"> div居中,文本左对齐 < / div >

其他回答

使用CSS flex属性:http://jsfiddle.net/cytr/j7SEa/6/show/

body {                       /* Centered */
  display: box;
  flex-align: center;
  flex-pack: center;
}

简单的http://jsfiddle.net/8pd4qx5r/

html {
  display: table;
  height: 100%;
  width: 100%;
}

body {
  display: table-cell;
  vertical-align: middle;
}

.content {
  margin: 0 auto;
  width: 260px;
  text-align: center;
  background: pink;
}

如果你的中心内容深在其他div,那么只有边缘可以拯救你。什么都没有。当我不使用Bootstrap这样的框架时,我总是面临这个问题。

出于某种原因,之前的答案对我都不起作用。这对我来说很管用,而且在不同的浏览器中也同样适用:

.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;
}
<body>
    <div style=" display: table; margin: 250 auto;">
        In center
    </div>
</body>

如果你想改变垂直位置,改变250的值,你可以根据你的需要安排内容。不需要给出宽度和其他参数。