我有一个div标签,宽度设置为800像素。当浏览器宽度大于800像素时,它不应该拉伸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页面居中L&R:

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

没有指定div宽度的定心:

body {
  text-align: center;
}

body * {
  text-align: initial;
}

body div {
  display: inline-block;
}

这有点像<center>标签,除了:

所有直接内联的子元素(例如。<h1>)的<center>也将定位到居中 根据浏览器默认值,内联块元素可以有不同的大小(与display:block设置相比)

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(它应该有一个设置的宽度):

.marginAutoLR
{
    margin-right:auto;
    margin-left:auto;
}

或者,添加边缘到你的div类,像这样:

.divClass
{
    width:300px;
    margin-right:auto;
    margin-left:auto;
}

位置:绝对,然后顶部:50%和左侧:50%将顶部边缘置于屏幕的垂直中心,左侧边缘置于水平中心,然后通过将margin-top添加到div高度的负数,即-100将其向上移动100,同样,margin-left也是如此。这使得div正好位于页面的中心。

# outPopUp { 位置:绝对的; 宽度:300 px; 身高:200 px; z - index: 15; 上图:50%; 左:50%; Margin: -100px 00 -150px; 背景:红色; } < div id = " outPopUp " > < / div >