【问题标题】:Vertically Centering content in html [duplicate]在html中垂直居中内容[重复]
【发布时间】:2014-08-06 09:24:09
【问题描述】:

我试图在<body> 中垂直居中<div>

我尝试这样做的原因是因为我正在尝试设计一个采用 Windows 8 Metro 开始屏幕样式的网站

有谁知道如何做到这一点?

【问题讨论】:

  • 贴出你试过的代码。
  • 欢迎来到 SO。在发布类似问题之前,您应该始终检查该问题是否不存在。谷歌搜索一下就可以看到结果
  • @j08691 我应该把它发到哪里? -_-
  • 编辑您的问题并将其发布到那里。

标签: html center vertical-alignment


【解决方案1】:

如果你想要垂直居中块,你可以使用这个技巧

边距是你的大小块的一半。

如果你使用它,你需要在你的块上设置大小。

html:

<div id="center"></div>

css:

#center{
    position:absolute;
    left:50%;
    top:50%;
    height:400px;
    width:600px;
    margin-left:-300px;
    margin-top:-200px;
}

演示:http://jsfiddle.net/ucbRs/

或者你也可以使用这个:

css:

#center{
    position:absolute;
    left:100px;
    top:100px;
    bottom:100px;
    right:100px;
}

演示:http://jsfiddle.net/ucbRs/1/

或者您也可以像这样使用 CSS3 属性 align-content

body{
    display:flex;
    flex-flow: row wrap;
    align-content:center;
}
#center{
    margin:0 auto;
}

演示:http://jsfiddle.net/ucbRs/3/

【讨论】:

    【解决方案2】:

    欢迎来到 SO!

    div 垂直居中实际上非常简单。

    div{
      margin-left: auto;
      margin-right: auto;
      text-align: center;
    }
    

    你有它。

    Demo

    你也可以考虑absolute centering:

    div{
      margin: auto;
      position: absolute;
      top: 0; left: 0; bottom: 0; right: 0;
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2013-11-29
      • 2011-09-04
      • 2013-03-29
      • 1970-01-01
      相关资源
      最近更新 更多