
如何让兄弟元素跟随最宽元素等宽
问题:
HTML 代码如下,需要让红色和灰色元素的宽度跟随绿色元素,保持一致:
item1item2item3
现有的 CSS 样式:
.item1 {
background: red;
}
.item2 {
background: gray;
}
.item3 {
min-width: 1300px;
background: greenyellow;
}解答:
可以使用 width: fit-content 来让 container 元素的内容根据内容实际大小进行调整。但此时滚动条会出现在 body 元素上。
解决方案是在 container 元素外层再套一层 wrap 元素,然后让 wrap 元素具有水平滚动条:
item1item2item3
.wrap {
width: 100%;
overflow-x: auto;
}
.container {
width: fit-content;
}
.item1 {
background: red;
}
.item2 {
background: gray;
}
.item3 {
min-width: 1300px;
background: greenyellow;
}如此一来,紅色和灰色元素的寬度就會自動跟隨綠色元素的寬度,保持一致,且滚动条会出现在 wrap 元素上。










