负边距不是解决方案——但什么才是?

Negative margin not the solution - but what is?

这是设计的一部分:

如您所见 - 它只是一个恰好位于两个 div 之间的按钮。代码很简单:

        <div class="uc-apply-widget1">
            <div class="top">
            </div>
            <div class="bottom">
                <a>Get Started</a>
            </div>
        </div>

.uc-apply-widget1
{
    .top
    {
        background-color:@primary-color;
        height:30rem;
    }
    .bottom
    {
        background-color:@primary-600;
        padding:0 1.6rem 1.6rem 1.6rem;

        a
        {
            margin-top:-2.8rem;
        }
    }
}

但是,我遇到了使用负边距的问题。我希望能够通过应用半高负边距将按钮移到底部 div 之外。虽然按钮确实向上移动,但它不会移动完整的 2.8 rem - 即使我应用 50rem,移动量也是相同的。

另一种解决方案是使用相对位置,它会向上移动按钮,但不会向上拖动底部 div。

所以我希望将按钮向上移动 n 个数量并将底部 div 高度减少 n 个数量 - 任何想法 - 我可能今天过得很糟糕。

使用

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

在你的按钮上

https://developer.mozilla.org/en-US/docs/Web/CSS/transform

这是实现您的设计的一种方法。

a 元素设置为具有 display: tableposition: absolute 顶部和左侧偏移分别为 0 和 50%。

display: table 规则将为您提供一个收缩至适合的宽度,这可能正是您所需要的。

然后您可以使用 CSS3 transform 属性 将元素在 X 和 Y 方向平移 -50% 以获得居中。

这里的优点是您不必为 a 元素指定尺寸。

.uc-apply-widget1 {
  width: 400px;
  margin: 0 auto;
}
.top {
  background-color: beige;
  height: 10rem;
}
.bottom {
  background-color: lightgray;
  height: 5rem;
  padding: 0 1.6rem 1.6rem 1.6rem;
  position: relative;
}
a {
  display: table;
  width: auto;
  margin: 0 auto;
  padding: 10px;
  border: 1px dotted blue;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
}
<div class="uc-apply-widget1">
  <div class="top">
  </div>
  <div class="bottom">
    <a>Get Started</a>
  </div>
</div>