我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。
当前回答
这也适用于ie浏览器,但汽车的利润率就不行。
.centered {
position: absolute;
display: inline-block;
left: -500px;
width: 1000px;
margin: 0 50%;
}
其他回答
使用CSS flex属性:http://jsfiddle.net/cytr/j7SEa/6/show/
body { /* Centered */
display: box;
flex-align: center;
flex-pack: center;
}
如果你有一些常规的内容,而不是只有一行文本,我所知道的唯一可能的原因是计算空白。
这里有一个例子:
HTML
<div id="supercontainer">
<div id="middlecontainer">
<div class="common" id="first">first</div>
<div id="container">
<div class="common" id="second">second</div>
<div class="common" id="third">third</div>
</div>
</div>
</div>
CSS
body {
margin: 0;
padding: 0;
}
.common {
border: 1px solid black;
}
#supercontainer {
width: 1200px;
background: aqua;
float: left;
}
#middlecontainer {
float: left;
width: 104px;
margin: 0 549px;
}
#container {
float: left;
}
#first {
background: red;
height: 102px;
width: 50px;
float: left;
}
#second {
background: green;
height: 50px;
width: 50px;
}
#third {
background: yellow;
height: 50px;
width: 50px;
}
因此,#supercontainer是你的“整个页面”,它的宽度是1200px。
# middlecontaintainer是你的网站内容的div;宽度为102px。在已知内容宽度的情况下,您需要将页面大小除为2,并从结果中减去内容宽度的一半: 1200 / 2 - (102 / 2) = 549;
是的,我也看到这是CSS的严重失败。
出于某种原因,之前的答案对我都不起作用。这对我来说很管用,而且在不同的浏览器中也同样适用:
.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;
}
旧代码中其他一些预先存在的设置将阻止div页面居中L&R:
隐藏在外部样式表链接中的其他类。 其他类嵌入到像img这样的东西中(比如旧的外部CSS打印格式控件)。 带有id和/或CLASSES的图例代码将与命名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 >