gpt4 book ai didi

html - 垂直对齐不适用于 flex 元素

转载 作者:太空宇宙 更新时间:2023-11-04 14:10:36 26 4
gpt4 key购买 nike

我尝试将纯文本垂直集中在 flexbox 元素内。

我决定将属性 display:table-cellvertical-align: middle 一起使用。但它似乎不能在 flexbox 元素中正常工作。

我怎样才能将它垂直居中,最好不使用包装器或定位,同时仍然用省略号截断长文本?

.container {
width: 400px;
height: 400px;
font-weight: 700;
border: 1px solid #d9d9d9;
display: flex;
flex-direction: column;
}

.item {
display: table-cell;
vertical-align: middle;
flex: 1 1;
background-color: cyan;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

.item:nth-of-type(2n) {
background-color: aliceblue;
}
<div class="container">
<div class="item">Hello, I'm very very long string! Hello, I'm very very long string!</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
</div>

View On CodePen

最佳答案

一种解决方案是将每个 flex 元素定义为自己的 flex 容器,以便将其内容垂直居中 align-items:center .为了保持 text-overflow 正常工作,向每个 flex 元素添加一个子元素,然后可以用省略号将其截断。

关于为什么 text-overflow 不能与 display:flexneither can David Wesst 一起工作,我无法提供简洁的解释。 .用他的话说:

It turns out that there really isn't a clean way to do this. If you're wondering how I came to that conclusion you can stop because I didn't. Those responsible for the specification did, and you can read the full conversation that started with a Mozilla bug report and leads to a whole mail group discussion about why it should (or, in this case, should not) be implemented as part of the spec.

这是一个工作示例:

.container {
width: 400px;
height: 400px;
font-weight: 700;
border: 1px solid #d9d9d9;
display: flex;
flex-direction: column;
}

.item {
display: flex;
align-items: center;
flex: 1;
background-color: cyan;
}

.item span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

.item:nth-of-type(2n) {
background-color: aliceblue;
}
<div class="container">
<div class="item"><span>Hello, I'm very very long string! Hello, I'm very very long string!</span></div>
<div class="item"><span>Hello</span></div>
<div class="item"><span>Hello</span></div>
<div class="item"><span>Hello</span></div>
</div>

另见:
Setting ellipsis on text from a flex container

关于html - 垂直对齐不适用于 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46853593/

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