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


当前回答

旧代码中其他一些预先存在的设置将阻止div页面居中L&R:

隐藏在外部样式表链接中的其他类。 其他类嵌入到像img这样的东西中(比如旧的外部CSS打印格式控件)。 带有id和/或CLASSES的图例代码将与命名div类冲突。

其他回答

<div></div>
div {
  display: table;
  margin-right: auto;
  margin-left: auto;
}
<body>
    <div style="width:800px; margin:0 auto;">
        centered content
    </div>
</body>

使用justify-content和align-items水平和垂直对齐div

https://developer.mozilla.org/de/docs/Web/CSS/justify-content https://developer.mozilla.org/en/docs/Web/CSS/align-items

超文本标记语言 的身体, .container { 高度:100%; 宽度:100%; } .container { 显示:flex; 对齐项目:中心; justify-content:中心; } .mydiv { 宽度:80 px; } < div class = "容器" > <div class="mydiv">h & v aligned</div> < / 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;
}

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

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

.item{
 align-self: center;
}

预览链接