【问题标题】:Negative margin not the solution - but what is?负边距不是解决方案 - 但什么是?
【发布时间】:2015-08-11 02:31:07
【问题描述】:

这是设计的一部分:

如您所见 - 它只是一个恰好位于两个 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 量 - 任何想法 - 我可能只是度过了糟糕的一天。

【问题讨论】:

    标签: css margin


    【解决方案1】:

    使用

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

    在你的按钮上

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

    【讨论】:

      【解决方案2】:

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

      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>

      【讨论】:

        猜你喜欢
        • 2018-04-02
        • 2022-06-12
        • 2013-07-03
        • 2019-03-09
        • 1970-01-01
        • 2022-01-03
        • 2019-12-02
        • 2021-01-09
        • 1970-01-01
        相关资源
        最近更新 更多