我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸div,但应该将它带到页面的中间。
当前回答
使用CSS flex属性:http://jsfiddle.net/cytr/j7SEa/6/show/
body { /* Centered */
display: box;
flex-align: center;
flex-pack: center;
}
其他回答
没有指定div宽度的定心:
body {
text-align: center;
}
body * {
text-align: initial;
}
body div {
display: inline-block;
}
这有点像<center>标签,除了:
所有直接内联的子元素(例如。<h1>)的<center>也将定位到居中 根据浏览器默认值,内联块元素可以有不同的大小(与display:block设置相比)
这也适用于ie浏览器,但汽车的利润率就不行。
.centered {
position: absolute;
display: inline-block;
left: -500px;
width: 1000px;
margin: 0 50%;
}
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 >
如果你有一些常规的内容,而不是只有一行文本,我所知道的唯一可能的原因是计算空白。
这里有一个例子:
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的严重失败。
将这个类添加到你想居中的div(它应该有一个设置的宽度):
.marginAutoLR
{
margin-right:auto;
margin-left:auto;
}
或者,添加边缘到你的div类,像这样:
.divClass
{
width:300px;
margin-right:auto;
margin-left:auto;
}