You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS Grid无固定列宽时如何实现自动换行,类似flex-wrap: wrap效果?

解答

这个需求可以实现,你现有代码的问题出在两处错误配置:

  1. 为.notification-content-wrapper设置的grid-auto-flow: column会强制所有子元素沿水平方向排列,直接覆盖了auto-fit的自动换行逻辑
  2. minmax()参数顺序写反,该属性规则为minmax(最小值, 最大值),你写的minmax(max-content, 0px)因为最小值大于最大值,会被浏览器判定为无效规则

修正后代码

.notification{
  background:lightgreen;
  padding:1rem;
  display:inline-block;
  width: 100%;
  box-sizing: border-box;
}

.notification-body{
  display: grid;
  grid-template-columns: auto 1fr auto;
  column-gap: 1rem;
  align-items: center;
}

.notification-content-wrapper{
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, max-content));
  gap: 1rem;
  align-items: center;
}
<div class="notification">
  <div class="notification-body">
    <p>there will<br>be always icon</p>
    
    <div class="notification-content-wrapper">
      <p>Notification message</p>
      <a href="#">notification link</a>
    </div>
    
    <p>there will be<br>always icon too</p>
  </div>
</div>

配置说明

  • grid-template-columns: repeat(auto-fit, minmax(min-content, max-content)):自动计算当前行可容纳的内容列数量,剩余空间不足放下下一个元素时自动换行,每列宽度始终匹配内容的实际长度
  • .notification-body的列模板设为auto 1fr auto,保证左右两侧的固定图标区域始终匹配内容宽度,中间的文字+链接区域占满剩余可用空间,避免整体内容提前换行

内容的提问来源于stack exchange,提问作者Pinnci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:36:03