javascript - CSS垂直居中

标签 javascript jquery html css

我知道有很多方法可以使用 CSS 居中。将任何东西水平居中是非常简单的。但是,如果您要将任何东西垂​​直居中,那就是一个全新的故事了。 我只想知道为什么我们不能只说 bottom-align:auto;顶部对齐:自动;就像我们想要水平居中的东西一样? 为什么看起来像居中一样简单的东西在水平居中时看起来如此简单?我知道有很多方法,但假设您有一个大小未知的元素,您希望将其置于另一个大小未知的元素的中心。

我已经坐了将近两天了,没有找到关于这个答案的好问题,我们有很多不同的方法来水平居中元素,但为什么没有一个 CSS 标准想出一种垂直居中的方法?这是一件坏事吗?它会让人哭泣还是随机进入分娩?它会熔化核 react 堆吗?

我们生活在 2014 年。似乎没有必要使用 Javascript 来做一些简单的事情,比如在另一个元素中居中。

编辑: 我的意思的代码示例: http://jsfiddle.net/VsakD/

CSS:

div.parentbox
{
    width:500px;
    height:500px;
    border-style:solid;
}

div.childbox
{
    width:300px;
    height:300px;   
    border-style:solid;
    margin-left:auto;
    margin-right:auto;
    margin-top:auto;
    margin-bottom:auto;
}

HTML:

<div class="parentbox">
    <div class="childbox">
        I shall be in the middle of parentbox regardless of its size!
    </div>
</div>

最佳答案

Can someone please highlight exactly why I can't just say margin-top:auto; margin-bottom:auto; to vertical align, which would be logical to assume would work since you do margin-left:auto; margin:right:auto; to horizontally align?

根据 Spec (10.6.2):

Inline replaced elements, block-level replaced elements in normal flow, 'inline-block' replaced elements in normal flow and floating replaced elements

If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0.

这就是为什么在这种情况下使用 top/bottom margin 并没有改变。

顺便说一句,为了在容器内垂直对齐一个 div 元素(具有未知尺寸),您可以遵循 this approach :

.parentbox {        
    text-align: center; /* Align inline elements center horizontally */
    font: 0/0 a; /* <-- remove the gap between inline(-block) elements */
}

.parentbox:before {
    content: ' ';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

.childbox {
    display: inline-block;
    vertical-align: middle;
    font: 1rem/1 Arial, sans-serif;  /* <-- Reset the font */
}

WORKING DEMO

关于javascript - CSS垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21533287/

相关文章:

javascript - 如何在javascript中每n个字符后插入一个字符?

javascript - 在面向对象的 Javascript 文件上使用 jQuery

javascript - 返回给定元素的所有数组索引

javascript - 如何选择多个元素

html - 转换不适用于 :before

javascript - 解析一些 JSON

javascript - 使用 React 更改文本区域中的光标位置

javascript - 从 CSS 脚本打开 Jquery 以来的文件夹

html - list.js javascript 库不工作

javascript - 辅助 onClick 事件不起作用