CSS 基于宽度而不是高度的垂直边距百分比

CSS % for vertical margin based on width instead of height

我想在我的 accountOrderButton 上方创建一个边距,以便它可以垂直居中。我正在尝试计算 parent div 高度的一半减去 child div 高度的一半。

这应该使按钮居中,但是我的 CSS 中的行 'margin-top: calc(50%);' 返回的是 parent div 的宽度。如何获取高度?

HTML

<div id="accountOrder">
    <div id="accountOrderButton">
        Order Now!
    </div>
</div>

CSS

#accountOrder {
    width: 400px;
    float: left;
    height:100%;
    text-align: center;
}
#accountOrderButton {
    width: 100px;
    height: 20px;
    margin: 0 auto;
    margin-top: calc(50%);    <---- returns width instead of height
    padding: 20px;
    background-color: <?php echo $data['secondary_color']; ?>;
    border-radius: 10px;
}

如果您想对齐块元素,请尝试使用 CSS flexbox。定义一个容器元素,其中包含以您喜欢的任何方式对齐的元素。它肯定适用于您的 % 方法,但是使用 flexbox 垂直对齐项目非常容易:

#accountOrder {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

您不需要任何边距、定位或其他东西。请注意,您必须删除 float: left;,因为浮动会阻止 flexbox 执行它的操作。

要使用 flexbox 获得 float: left; 等效定位,只需使用:

.container {
    display: flex;
}

top代替margin-top,不加calc,还要加left: 50%;,加上transform: translate(-50%, -50%),把它往后移自己高和宽的一半。这也需要在 child 上使用绝对位置,在 parent 上使用相对位置:

#accountOrder {
    width: 400px;
    float: left;
    height:100%;
    text-align: center;
    position: relative; /* added */
}
#accountOrderButton {
    position: absolute; /* added */
    width: 100px;
    height: 20px;
    top: 50%;  /* changed */
    left: 50%; /* added */
    transform: translate(-50%, -50%); /* added */
    padding: 20px;
    background-color: <?php echo $data['secondary_color']; ?>;
    border-radius: 10px;
}

由于这是一个常见的误解,可能值得将@CBroe 的评论转化为答案,以便其他人轻松找到它。

The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for margin-top and margin-bottom as well.

http://w3.org/TR/CSS21/box.html#margin-properties

另请注意,calc(50%) 根本不计算 任何东西,与 50%.

相同