我有一个带有左侧和右侧的标头。左侧包含一些我想保留在一行上的文本,如果需要,可以用省略号将其截断。但是,当我对它应用white-space: nowrap
时,整个标头都将超出其容器。这就是我的意思:
.container {
width: 300px;
height: 400px;
border: 1px solid black;
}
.header {
height: 80px;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
border: 1px solid red;
}
.header-right,
.header-left {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid blue;
}
.title {
text-overflow: ellipsis;
white-space: nowrap;
}
img {
height: 20px;
width: 20px;
margin: 10px;
}
<div class="container">
<div class="header">
<div class="header-left">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
<span class="title">Title: Keep me on a single line</span>
</div>
<div class="header-right">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
</div>
</div>
</div>
有人知道如何将标题保持在一行上,但将其截断以使标题不会超出范围吗?
答案 0 :(得分:3)
您需要通过添加min-width:0
来禁用默认最小宽度,并通过添加flex-shrink:0;
并添加overflow:hidden
.container {
width: 300px;
height: 400px;
border: 1px solid black;
}
.header {
height: 80px;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
border: 1px solid red;
}
.header-right,
.header-left {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid blue;
min-width:0; /* Added */
}
.title {
text-overflow: ellipsis;
white-space: nowrap;
overflow:hidden; /* Added */
}
img {
height: 20px;
width: 20px;
margin: 10px;
flex-shrink:0; /* Added */
}
.header-right {
flex-shrink:0; /* Added */
}
<div class="container">
<div class="header">
<div class="header-left">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
<span class="title">Title: Keep me on a single line</span>
</div>
<div class="header-right">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
<img src="https://image.flaticon.com/icons/png/128/181/181548.png">
</div>
</div>
</div>
相关:
Why don't flex items shrink past content size?(了解min-width
)
Why is a flex-child limited to parent size?(了解flex-shrink
)