如何实现CSS Grid三列布局:两侧列同宽,中间列占满空间
解决方案:三列等宽外侧+自适应中间列布局
要实现左右两列宽度一致、中间列占据所有剩余空间的布局,同时保证外侧列自适应内容宽度(不强制换行),可以通过Grid布局的minmax()函数精准控制列宽:
.container { display: grid; /* 左右列:至少容纳自身内容(不换行),最多平分剩余空间(保证等宽);中间列占满所有可用空间 */ grid-template-columns: minmax(max-content, 1fr) 1fr minmax(max-content, 1fr); gap: 2rem; }
关键逻辑说明
minmax(max-content, 1fr):为左右列设置宽度范围:- 下限
max-content确保列宽至少能容纳内部所有内容(避免强制换行); - 上限
1fr让左右列平分容器剩余空间,从而严格保持等宽,即使其中一列内容更长。
- 下限
- 中间列的
1fr会自动占据容器除左右列和间隙外的全部剩余空间,完全满足“尽可能宽”的需求。
完整代码示例
.container { display: grid; grid-template-columns: minmax(max-content, 1fr) 1fr minmax(max-content, 1fr); gap: 2rem; margin-bottom: 2rem; } .item { padding: .2rem; } .item1 { background-color: lightgreen; justify-self: center; /* 可选:让列内内容居中显示 */ } .item2 { text-align: center; background-color: lightblue; } .item3 { background-color: lightpink; justify-self: center; /* 可选:让列内内容居中显示 */ }
<div class="container"> <div class="item item1">Column 1<br>This is where this column needs to be</div> <div class="item item2">Column 2<br>Now it is wide :)<br>And perfectly centered!</div> <div class="item item3">Column 3</div> </div> <div class="container"> <div class="item item1">Short</div> <div class="item item2">Middle column takes all remaining space</div> <div class="item item3">Longer content that would normally make this column wider</div> </div>
适配动态内容
该方案完全支持外侧列的动态内容需求:无论列内是链接、样式化按钮、SVG组还是固定宽度图片,max-content都会自动取列内最宽元素的宽度作为列的最小宽度,同时保持左右列等宽。
内容的提问来源于stack exchange,提问作者Nikolas
相关产品推荐
相关产品推荐

