gpt4 book ai didi

css - 垂直居中,右对齐,多行文本在绝对定位的 div 与 flexbox parent

转载 作者:行者123 更新时间:2023-12-03 18:18:26 27 4
gpt4 key购买 nike

我有一些绝对定位的 div,其中包含两行文本,一个 h2 和一个 p。我试图让文本成为:在绝对定位的 div 内垂直居中,右对齐,并且在 h2 和 p 标签之间有一个换行符。

绝对定位的 div 包含在父级中,所以我想我可以使用 flexbox 来解决这个问题,但事实证明它比预期的要难。我给了父级 display:flex 和 align-items:center ,它们垂直居中。但是后来我的 h2 和 p 在同一条线上,没有换行符。

然后我使用 flex-direction: column 创建了一个换行符,但是文本不再垂直居中。如果我使用 align-items:flex-end 和 flex-direction:column,文本将右对齐并且 h2 和 p 之间会有一个换行符,但它们不会垂直居中。

margin-right:auto 据说可以右对齐元素,但结合 align-items:center 和 flex-direction:column,它不起作用。 float:right 也不起作用。

我的标记如下所示:

    <div class = "col-sm-12">
<div class = "row overlay-container">
<img src = "_img/top-right@4x.png" class = "img-responsive grid-image" alt = "top-right@4x image" />
<div class = "overlay overlay-2">
<h2>Recent Work</h2>
<p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->
</div> <!-- /row -->
</div> <!-- /top right -->

其中 overlay 是覆盖容器内绝对定位的 div。叠加层是位于图像一部分之上的框。上面提到的display:flex等属性都在overlay类上。

似乎无论我怎么尝试,我只能让三个条件中的两个起作用。使用 flexbox 不是必需的,但我认为它会使文本垂直居中变得容易。谁能帮忙?

最佳答案

这是一个如何使用 display: flex 居中的示例

堆栈片段

body {
margin: 0;
}
.overlay {
width: 300px;
margin-top: 5vh;
height: 90vh;
border: 1px solid;

display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
<div class = "overlay overlay-2">
<h2>Recent Work</h2>
<p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->


已更新

在某些情况下,可能需要使用自动边距,因为使用 justify-content 居中时(使用 flex-direction: column 时)的默认行为是,当内容不适合时,它会在顶部和底部溢出。

堆栈片段

body {
margin: 0;
}
.overlay {
width: 300px;
margin-top: 5vh;
height: 90vh;
border: 1px solid;

display: flex;
flex-direction: column;
/*justify-content: center; removed */
align-items: center;
overflow: auto; /* scroll when overflowed */
}

.overlay h2 {
margin-top: auto; /* push to the bottom */
}
.overlay p {
margin-bottom: auto; /* push to the top */
}
<div class = "overlay overlay-2">
<h2>Recent Work</h2>
<p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->


更新 2

这里中间有第三个元素,当不适合时会滚动。

堆栈片段

body {
margin: 0;
}
.overlay {
width: 300px;
margin-top: 5vh;
height: 90vh;
border: 1px solid;

display: flex;
flex-direction: column;
align-items: center;
}

.overlay p:first-of-type {
overflow: auto; /* scroll when overflowed */
}

.overlay h2 {
margin-top: auto; /* push to the bottom */
}
.overlay p:last-of-type {
margin-bottom: auto; /* push to the top */
}
<div class = "overlay overlay-2">
<h2>Recent Work</h2>
<p>
Lorem ipsum dolor<br>
Lorem ipsum dolor<br>
Lorem ipsum dolor<br>
Lorem ipsum dolor<br>
Lorem ipsum dolor<br>
Lorem ipsum dolor<br>
Lorem ipsum dolor<br>
</p>
<p>Maybe a link for more</p>
</div> <!-- /overlay -->


另一个例子:

关于css - 垂直居中,右对齐,多行文本在绝对定位的 div 与 flexbox parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807426/

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