场景:宽度一定的情况下右边自适应,左边被挤压。
需要的效果如下:
flex 的三个参数分别对应:flex-grow、flex-shrink、flex-basis。
- flex-grow:定义项目的放大比例,默认为0。即如果存在剩余空间,也不放大。
- flex-shrink:定义项目的缩小比例,默认为1。即如果空间不足,该项目将缩小。
- flex-basis:定义在分配多余空间之前,项目占据的主轴空间。
简单说,左边的设置flex: 0 1 auto; 右边的设置flex: 0 0 auto;
直接上Demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {
background-color: lightgrey;
padding: 10px 0;
display: flex;
max-width: 410px;
margin-bottom: 2px;
}
.less-important {
background-color: lightpink;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 0 5px;
flex: 0 1 auto;
}
.more-important {
background-color: lightgreen;
white-space: nowrap;
padding: 0 5px;
flex: 0 0 auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="less-important">Truncate this text because it is less important</div>
<div class="more-important">The important text</div>
</div>
<div class="parent">
<div class="less-important">No ellipsis</div>
<div class="more-important">Important stuff</div>
</div>
<div class="parent">
<div class="less-important">Less important content</div>
<div class="more-important">Way more important info that will cause ellipsis</div>
</div>
</body>
</html>