I have a header with a left and right side. The left side contains some text which I want to keep on a single line, truncating with ellipsis if needed. However, when I apply white-space: nowrap
to it then the whole header goes outside its container. Here's what I mean:
.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>
Does anyone know how to keep the title on a single line but truncate it so the header doesn't go outside the bounds?
You need to disable the default minimun width by adding min-width:0
and disable the shriking for the images and their container by adding flex-shrink:0;
and add 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>
Related:
Why don't flex items shrink past content size? (To understand the min-width
)
Why is a flex-child limited to parent size? (To understand the flex-shrink
)