gpt4 book ai didi

javascript - 使用相对位置和 top 属性来定位 Flexbox 的子元素(right 属性有效,但 top 无效)

转载 作者:行者123 更新时间:2023-11-28 04:25:02 25 4
gpt4 key购买 nike

<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%。我假设这与 flex 盒和定位有关。我应该怎么做才能解决这个问题?

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

最佳答案

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

要查看您的顶部/底部定位是否生效,请执行以下任一操作

  • 为包含元素指定一个高度,以便根据该高度计算百分比值

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

使用%

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

.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>

关于javascript - 使用相对位置和 top 属性来定位 Flexbox 的子元素(right 属性有效,但 top 无效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com