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


当前回答

将这个类添加到你想居中的div(它应该有一个设置的宽度):

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

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

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

其他回答

如果你有一些常规的内容,而不是只有一行文本,我所知道的唯一可能的原因是计算空白。

这里有一个例子:

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的严重失败。

.middle {
   margin:0 auto;
   text-align: center;
}

/*它把div放到中心*/

<body>
    <div style=" display: table; margin: 250 auto;">
        In center
    </div>
</body>

如果你想改变垂直位置,改变250的值,你可以根据你的需要安排内容。不需要给出宽度和其他参数。

<body>
    <div style="width:800px; margin:0 auto;">
        centered content
    </div>
</body>

只需在body标签之后使用center标签,并在body结束之前结束center标签:

<body>
    <center>
        ... Your code here ...
    </center>
</body>

在我尝试过的所有浏览器中,这都是可行的。