
css如何实现兄弟元素宽度跟随最长的一个
问题描述
在html页面中,存在三个水平排列的div元素,分别为红色、灰色和绿色背景。要求红色和灰色元素的宽度自动跟随绿色元素的宽度,并撑满它们的父容器。现有代码如下:
item1item2item3
解决方案
立即学习“前端免费学习笔记(深入)”;
可以使用 fit-content 属性来解决此问题。给父容器 container 添加width: fit-content property,即可实现兄弟元素宽度跟随最长的一个。
代码实现
item1item2item3
.wrap {
width: 100%;
overflow-x: auto;
}
.container {
width: fit-content;
}
.item1 {
background: red;
}
.item2 {
background: gray;
}
.item3 {
min-width: 1300px;
background: greenyellow;
}注意事项
使用 fit-content 可能会导致滚动条出现在父容器中,因此建议在 container 外部再套一层 wrap 元素,并设置 overflow-x: auto 属性。










