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


当前回答

这可以通过flex容器轻松实现。

.container{
 width: 100%;
 display: flex;
 height: 100vh;
 justify-content: center;
}

.item{
 align-self: center;
}

预览链接

其他回答

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 >

<div></div>
div {
  display: table;
  margin-right: auto;
  margin-left: auto;
}
.middle {
   margin:0 auto;
   text-align: center;
}

/*它把div放到中心*/

为了让它在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;
}
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%”仅为示例。在实际项目中,您可以删除此属性。