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

如何用Flexbox实现盒子精准上下对齐及容器高度切换功能

实现方案

HTML 结构

<div class="container">
  <button class="toggle-btn">展开/收起</button>
  <div class="content-wrapper">
    <div class="row row-initial">
      <div class="col">text1</div>
      <div class="col">text2</div>
      <div class="col">text3</div>
      <div class="col">text4</div>
    </div>
    <div class="row row-expandable">
      <div class="col"></div>
      <div class="col">text5</div>
      <div class="col">text6</div>
      <div class="col"></div>
    </div>
  </div>
</div>

CSS 样式

.container {
  display: inline-flex;
  flex-direction: column;
  gap: 12px;
}

.content-wrapper {
  display: grid;
  grid-template-columns: repeat(4, max-content);
  gap: 16px;
  transition: grid-template-rows 0.3s ease;
  /* 默认收起状态,展开行高度压缩为0 */
  grid-template-rows: auto 0fr;
}

.content-wrapper.expanded {
  /* 展开状态,展开行高度自适应内容 */
  grid-template-rows: auto 1fr;
}

.row {
  display: contents; /* 让子元素直接成为网格项,消除额外层级影响 */
}

.col {
  white-space: nowrap; /* 保证文本不换行,维持内容原生宽度 */
}

.row-expandable .col {
  overflow: hidden; /* 收起时隐藏溢出内容 */
}

.toggle-btn {
  padding: 8px 16px;
  cursor: pointer;
}

JS 逻辑

const toggleBtn = document.querySelector('.toggle-btn');
const contentWrapper = document.querySelector('.content-wrapper');

toggleBtn.addEventListener('click', () => {
  contentWrapper.classList.toggle('expanded');
});

关键说明

  • 展开收起实现:通过grid-template-rows在auto+0fr和auto+1fr之间切换,0fr会将展开行高度压缩为0(配合overflow:hidden隐藏内容),1fr让行高度自适应内容,完全避开固定height、max-height和scaleY属性。
  • 精准对齐:利用网格列布局,将text2与text5、text3与text6分别放在同一列,实现天然对齐;grid-template-columns使用max-content让列宽完全适配内容,无需手动设置宽度类。
  • 内容宽度适配:外层.container使用inline-flex,宽度由内部内容自动决定,符合“flex items仅适配内容宽度”的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:27:49