【问题标题】:Position child elements of a flexbox with position relative and the top property (right property works but top doesn't)使用 position relative 和 top 属性定位 flexbox 的子元素(right 属性有效,但 top 无效)
【发布时间】:2017-07-17 09:35:49
【问题描述】:
<div class="b-wrapper d-flex d-flex-center">
     <div class="inner-wrapper">
         <h2 class="b-animate h b-from-top b-delay03">Project 3</h2>
         <p class="b-animate p b-from-right b-delay03">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
     </div>
 </div>

当尝试将position: relative; right: -100%; 的样式添加到 h2 元素时,文本会向右移动 100%。但是,如果我将样式更改为position: relative; top: -100%;,则文本拒绝向上移动 100%。我假设这与 flexbox 和定位有关。我应该怎么做才能解决这个问题?

.d-flex-center {
    justify-content: center;
    align-items: center;
}
.d-flex {
    display: flex!important;
}
.b-wrapper .inner-wrapper {
    margin: 0 15px -17px 15px;
}

【问题讨论】:

  • 您能告诉我们您要实现的功能是什么吗?这样我们就可以提出替代方案。

标签: javascript jquery html css flexbox


【解决方案1】:

顶部定位在这里不起作用,因为您使用的是百分比值,而容器没有高度。正值也一样。

要查看您的顶部/底部定位是否生效

  • 给包含的元素一个高度,这样百分比值就会根据这个计算出来

  • 使用像素值进行顶部/底部定位

使用%

父容器必须具有指定的高度,以便正确计算百分比。

.d-flex-center {
    justify-content: center;
    align-items: center;
}
.d-flex {
    display: flex!important;
}
.b-wrapper .inner-wrapper {
    margin: 0 15px -17px 15px;
}
.inner-wrapper {
  height: 150px;    /* container height */
}
h2 {
  position: relative;
  right: -40%;
  top: -20%;      /* -20% is now equivalent to -30px (20% of 150px height) */
}
<div class="b-wrapper d-flex d-flex-center">
     <div class="inner-wrapper">
         <h2 class="b-animate h b-from-top b-delay03">Project 3</h2>
         <p class="b-animate p b-from-right b-delay03">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
     </div>
 </div>

使用px

像素值将始终保持一致,因为它不是基于另一个值计算的。 (无需在父容器上指定高度。)

.d-flex-center {
    justify-content: center;
    align-items: center;
}
.d-flex {
    display: flex!important;
}
.b-wrapper .inner-wrapper {
    margin: 0 15px -17px 15px;
}
h2 {
  position: relative;
  right: -40%;
  top: -30px;    /* -30px === -30px */
}
<div class="b-wrapper d-flex d-flex-center">
     <div class="inner-wrapper">
         <h2 class="b-animate h b-from-top b-delay03">Project 3</h2>
         <p class="b-animate p b-from-right b-delay03">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
     </div>
 </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多