【问题标题】:Using translate and calc() together一起使用 translate 和 calc()
【发布时间】:2017-10-18 16:43:57
【问题描述】:

我有一个垂直放置的元素,如下所示:

position: absolute;
top: 50%;
transform: translateY(-50%)

这会直接在屏幕中间弹出。问题是我有一个页脚,所以 div 总是必须再高 150px 才能使 div 居中。

有没有办法结合一个 sass 函数或 calc() 来让我的 div 向上移动?

【问题讨论】:

  • 向下滚动时会出现问题吗?

标签: css css-position absolute calc


【解决方案1】:

你可以在你的上衣上使用 calc:

top: calc(50% - 150px);

或者负边距也可以:

margin-top: -150px;

【讨论】:

    【解决方案2】:

    现在大多数现代浏览器在top 和内部translateY 上都支持calc()。检查下面的 sn-p 以供参考。如需浏览器支持,请查看caniuse

    .parent {
      height: 200px;
      position: relative;
      background: #ccc;
    }
    
    .child {
      position: absolute;
      min-height: 50px;
      width: 100%;
      background: cyan;
      top: 50%;
      transform: translateY(calc(-50% - 50px));
    }
    
    .footer {
      position: absolute;
      bottom: 0;
      height: 50px;
      width: 100%;
      background: red;
    }
    <div class="parent">
      <div class="child">
      </div>
      <div class="footer">
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2014-09-23
      • 2017-07-18
      • 2014-10-20
      • 1970-01-01
      • 2021-05-30
      • 2013-08-04
      相关资源
      最近更新 更多