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


当前回答

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

其他回答

在我的情况下,手机屏幕大小是未知的,这是我所做的。

HTML

<div class="loadingImg"></div>

CSS

.loadingImg{
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 9999999;
    border: 0;
    background: url('../images/loading.gif') no-repeat center;
    background-size: 50px 50px;
    display: block;
    margin: 0 auto;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

JavaScript(在需要显示此DIV之前)

$(".loadingImg").css("height",$(document).height());
$(".loadingImg").css("width",$(document).width());
$(".loadingImg").show();

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

这里有一个例子:

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,那么只有边缘可以拯救你。什么都没有。当我不使用Bootstrap这样的框架时,我总是面临这个问题。

Div在父元素中垂直和水平居中,不固定内容大小

在这个页面上有一个很好的概述,有几个解决方案,太多的代码在这里分享,但它显示了什么是可能的…

就我个人而言,我最喜欢这个著名的转换转换-50%技巧的解决方案。它适用于固定(%或px)和未定义的元素高度和宽度。 代码非常简单:

HTML:

<div class="center"><div>

CSS:

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  -moz-transform: translate(-50%, -50%); /* Firefox */
  -ms-transform: translate(-50%, -50%);  /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Safari and Chrome*/
  -o-transform: translate(-50%, -50%); /* Opera */
  transform: translate(-50%, -50%);

  /* optional size in px or %: */
  width: 100px;
  height: 100px;
}

这里有一把小提琴,展示了它的工作原理

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

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

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

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