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

CSS Grid列随内容伸缩,其余列保持固定宽度的实现方案

实现可动态收缩的Grid列布局

完整解决方案代码

HTML

<div class="main">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
  <div>Item 4</div>
  <div>Item 5</div>
</div>

CSS

.main {
  display: grid;
  /* 每列最大宽度为视口20%,最小宽度由内容自动适配 */
  grid-template-columns: repeat(5, minmax(auto, 20vw));
  overflow-x: auto;
  margin: 0;
  padding: 0;
}

.main div {
  /* 让子元素默认撑满列宽 */
  width: 100%;
  padding: 1rem;
  box-sizing: border-box;
}

.main div:nth-child(1) { background: red; }
.main div:nth-child(2) { background: blue; }
.main div:nth-child(3) { background: yellow; }
.main div:nth-child(4) { background: green; }
.main div:nth-child(5) { background: purple; }

.shrink {
  /* 强制子元素宽度为40px */
  width: 40px;
  /* 可选:处理溢出内容,避免换行 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

JavaScript

for (const column of document.querySelectorAll('.main div')) {
  column.addEventListener("mouseover", (event) => {
    column.classList.toggle('shrink');
  });
}

关键调整说明

  1. Grid列宽设置
    原代码用repeat(5, 20%)固定列宽,会覆盖子元素的width属性导致收缩失效。改用minmax(auto, 20vw):

    • auto:列宽自动适配子元素内容宽度
    • 20vw:限制列的最大宽度为视口宽度的20%,保证默认状态下每列占页面20%
  2. 容器横向滚动
    添加overflow-x: auto,当某列收缩到40px后,总列宽变为40px + 4*20vw,可能超过视口宽度,此时容器会显示横向滚动条,避免列被强制压缩或换行。

  3. 子元素宽度控制
    默认给子元素设置width:100%,让其撑满列宽;添加.shrink类时强制width:40px,触发Grid列自动收缩到对应宽度。

效果验证

  • 默认状态:5列各占视口20%宽度,子元素撑满列宽
  • 鼠标悬停任意列:该列收缩至40px,其余列保持20%宽度
  • 再次悬停:该列恢复至20%最大宽度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:45:13