我有一个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的严重失败。

其他回答

这也适用于ie浏览器,但汽车的利润率就不行。

.centered {
    position: absolute;
    display:  inline-block;
    left:     -500px;
    width:    1000px;
    margin:   0 50%;
}

没有指定div宽度的定心:

body {
  text-align: center;
}

body * {
  text-align: initial;
}

body div {
  display: inline-block;
}

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

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

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;
}

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

您的意思是要垂直居中还是水平居中?你说你指定高度为800像素,并希望div在宽度大于该值时不拉伸…… 要水平居中,可以使用margin: auto;属性。此外,你还必须确保body和html元素没有任何边距或填充:

html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }
body, html {
    display: table;
    height: 100%;
    width: 100%;
}
.container {
    display: table-cell;
    vertical-align: middle;
}
.container .box {
    width: 100px;
    height: 100px;
    background: red;
    margin: 0 auto;
}

http://jsfiddle.net/NPV2E/

“body”标签的“width:100%”仅为示例。在实际项目中,您可以删除此属性。