flex 布局实现溢出隐藏
1.
如下 flex 布局,文本是 flex item 的直接子元素,一切都符合预期:
html
<div class="flex-parent">
<div class="flex-child">
Text to truncate here.
Text to truncate here.
Text to truncate here.
Text to truncate here.
Text to truncate here.
Text to truncate here.
Text to truncate here.
Text to truncate here.
123 123
</div>
<div class="flex-child">
Other stuff.
</div>
</div>
css
/* Text is directly within flex child,
so doing the wrapping here */
.flex-child{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
当文本不是直接子元素,溢出隐藏就会失效:
html
<div class="flex-parent">
<div class="flex-child">
<h2>Text to truncate here.Text to truncate here.Text to truncate here.Text to truncate here.Text to truncate here.</h2>
</div>
<div class="flex-child">
Other stuff.
</div>
</div>
css
.flex-parent{
display:flex;
outline:1px solid red;
}
.flex-child {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
预览
https://jsbin.com/kacawab/edit?html,css,output
css
/* Text is a header now,
so need to truncate there for it to work */
.flex-child > h2 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
预览
https://jsbin.com/dakinem/edit?html,css,output
2.
html
<div class="target">
<div class="target-title">
<h2>
Text here is very very long that it might
get truncate if this box get resized too small
</h2>
</div>
<div class="target-button">
Button
</div>
</div>
css
.target {
display: flex;
justify-content: space-between;
align-items: center;
}
.target-title h2 {
overflow: hidden;
padding: 5px;
text-overflow: ellipsis;
white-space: nowrap;
}
.target-button {
padding: 5px 10px;
background: #2196F3;
color: white;
}
如上布局是没有溢出隐藏效果的,需要添加如下代码:
css
/* 重点 */
.target-title{
min-width:0;
}
预览
https://jsbin.com/soxonif/edit?html,css,output