【问题标题】:How to vertically and horizontally align a div into center of page [duplicate]如何将div垂直和水平对齐到页面中心[重复]
【发布时间】:2014-02-11 16:20:19
【问题描述】:

我已经阅读了很多关于如何在页面上居中放置元素或 div 的提示,但似乎都没有。我什至制作了一个 JSFiddle 来尝试一下:

http://jsfiddle.net/aLye7/

我确定这一定是一个简单的答案,但我无法弄清楚。任何帮助将不胜感激。

<body>
  <div class="intro-area">
    <div class="intro-text">
      <p>This is a paragraph I want to center on the page.</p>
      <p>This is another paragraph I want to center on the page.</p>
    </div>
  </div>
</body>

.intro-area {
  background-color: #e7e7e7;
  display: table;
  text-align: center;
}

.intro-text {
  display: table-cell;
  vertical-align: middle;
}

另外,在 JSFiddle 中,我通过 javascript 中的 window.height 函数动态拉动 .intro-area div 的高度。这就是它在我的项目中的使用方式。

【问题讨论】:

  • 在提出新问题之前,请先查看现有答案。见:stackoverflow.com/…
  • 今天感觉很慷慨:jsfiddle.net/aLye7/2;仅供参考:js 没有必要这样做。
  • @Diodeus 我想要居中的元素的父 div 通过 JS 获得它的高度有什么区别吗?因为这本质上就是为什么我在查看其他问题后提出的问题。没有其他人这样做。
  • @brouxhaha 你就是那个男人!谢谢!

标签: javascript css centering


【解决方案1】:

对于这种特定情况,添加以下内容以强制 html、body 和包含 div 的高度为 100%:

html, body, .intro-area {
    height: 100%;
}

以及从 html 和 body 中删除默认填充和边距的以下内容:

html, body {
    margin: 0;
    padding: 0;
}

使用此方法无需 JavaScript。

DEMO

【讨论】:

    猜你喜欢
    • 2014-01-22
    • 1970-01-01
    • 2017-12-29
    • 2020-10-21
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2019-07-15
    相关资源
    最近更新 更多