- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我尝试将纯文本垂直集中在 flexbox 元素内。
我决定将属性 display:table-cell
与 vertical-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>
最佳答案
一种解决方案是将每个 flex 元素定义为自己的 flex 容器,以便将其内容垂直居中 align-items:center
.为了保持 text-overflow
正常工作,向每个 flex 元素添加一个子元素,然后可以用省略号将其截断。
关于为什么 text-overflow
不能与 display:flex
和 neither 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>
关于html - 垂直对齐不适用于 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46853593/
我是一名优秀的程序员,十分优秀!