【问题标题】:why does "top: -50%;" not work on this situation but "left: -50%" does为什么“顶部:-50%;”在这种情况下不起作用,但“left:-50%”可以
【发布时间】:2016-02-18 20:22:06
【问题描述】:

这是我的示例代码:

.container {
    position: absolute;
    left: 50%;
    top: 50%;
}

.container .box{
    position: relative;
    width: 200px;
    height: 200px;
    left: -50%;
    top: -50%;
    background-color: red;
}

.container 元素中,我没有设置宽度和高度。但是这个例子适用于水平面,但不适用于垂直面。其实top的计算值是-100px,但是浏览器并没有将.box元素100px移到顶部。

【问题讨论】:

标签: html css


【解决方案1】:

这看起来像是 webkit 中的一个错误。如果您搜索他们的错误跟踪器,您会看到它不时出现在那里(1476223570)。

他们甚至为此问题提供了一个测试用例,但出人意料地失败了。你可以在这里试试:https://bug-14762-attachments.webkit.org/attachment.cgi?id=15679

【讨论】:

    【解决方案2】:

    margin-top: -50%; 可以解决问题。

    【讨论】:

    • 没有。如果margin-top 指定为百分比,它将相对于包含框的宽度进行计算。所以当我设置width: 400pxheight: 100px时,top: -50%的计算值是-50px,而margin-top: -50%-200px
    • 没错,在这种情况下你必须定义 margin-top: -50px;
    • 假设如果定义了盒子 height: 200px; 上边距将是 -100px;
    【解决方案3】:

    我知道为时已晚,但这里将top: -50% 替换为transform: translateY(-50%);

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2010-12-29
      • 1970-01-01
      • 2021-08-05
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多