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

Safari(WebKit)中Flex布局使用aspect-ratio时内容溢出问题

问题解决:Safari中日历Flex容器重叠问题

问题背景

开发日历组件时,要求每个日历单元格保持aspect-ratio: 1,容器在移动端为列布局、桌面端为行布局。该组件在Chrome等浏览器显示正常,但在Safari中两个日历出现重叠,Flex容器未正确自适应内容。

示例代码

HTML

<div>
  <div class="picker-months">
    {/**生成2个月份容器 */}
    {[1, 2].map((week, index) => (
      <div class="picker-month" key={index}>
        <div class="picker-month-caption">February</div>
        <table class="picker-month-grid">
          <tbody>
            {/**生成4行日期 */}
            {[1, 2, 3, 4].map((week, index) => (
              <tr class="picker-week" key={index}>
                {/**生成7天单元格 */}
                {Array.from({ length: 7 }, (_, i) => i + 1).map(
                  (day, index) => (
                    <td class="picker-day" key={index}>
                      <button class="rdp-day_button picker-day-button">
                        {day}
                      </button>
                    </td>
                  )
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    ))}
  </div>
</div>

CSS

/* 补全Flex容器样式,实现移动端列、桌面端行布局 */
.picker-months {
  display: flex;
  flex-direction: column;
  gap: 1rem; /* 添加间距避免拥挤 */
}

@media (min-width: 768px) {
  .picker-months {
    flex-direction: row;
  }
}

.picker-month {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  min-width: 0; /* 防止Safari中Flex子项过度收缩 */
}

.picker-month-grid {
  text-align: center;
  width: 100%;
  table-layout: fixed; /* 强制表格按固定布局计算宽度,解决Safari宽度计算问题 */
  border-collapse: separate;
  border-spacing: 0.2rem; /* 替代单元格margin,避免布局冲突 */
}

.picker-weekdays {
  display: flex;
}

.picker-week {
  display: flex;
}

.picker-day {
  flex-grow: 1;
  display: flex;
  aspect-ratio: 1;
}

.picker-day-button {
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  aspect-ratio: 1;
  font-size: 0.8rem;
}

效果对比

Safari修复前显示

Safari中日历重叠效果

Chrome正常显示效果

Chrome中日历正常显示效果

问题原因与解决方案解析

  1. Safari Flex容器宽度计算缺陷:Safari对包含表格的Flex子项宽度计算存在兼容性问题,默认会过度收缩子容器导致重叠。给.picker-month添加min-width: 0可允许子项合理收缩,同时配合表格table-layout: fixed强制宽度按比例分配。
  2. 表格布局优化:使用table-layout: fixed让表格列宽度均匀分配,用border-spacing替代单元格margin-bottom,避免布局冲突,确保aspect-ratio: 1能正确作用于每个单元格。
  3. 补全Flex容器规则:明确.picker-months的Flex布局逻辑,通过媒体查询实现移动端/桌面端布局切换,添加gap控制月份间距。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:36:12