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

CSS Flex布局对齐异常求助:教室日程日历事件排布问题

解决教室日历事件的Flex布局对齐问题

你的问题核心在于所有事件直接放在了一个横向Flex容器里——默认display:flex的主轴是水平方向,不管你给子元素加多少margin-top,它们都会被强制排在同一行,垂直margin只会撑大容器高度,不会改变元素的水平排列逻辑。

要实现「同时间段事件横向并排,不同时间段垂直排列」,需要按时间段对事件进行分组,调整布局结构:

  1. 外层容器改为垂直排列,用来承载不同时间段的分组
  2. 每个时间段单独创建一个横向Flex容器,用来放置该时间段内的所有事件

修改后的代码示例

<div style="position:relative; display:flex; flex-direction:column; gap: 8px;" id="15_2023_1_20">
    <!-- 09:00-12:00 时间段 -->
    <div style="display:flex; gap:1px;">
        <div style="height: 48px; flex: 1 1 0%; background-color: rgb(221, 126, 107); color: rgb(102, 102, 102); border-radius: 3px; display: flex; align-items: center; justify-content: center; overflow: hidden; padding: 0px 5px; cursor: pointer;" class="mod-lezione c340 d35970" data-toggle="tooltip" data-placement="top" data-id="340" data-cal-id="112880" data-html="true" title="" data-original-title="Recitazione 04/22<br>Teacher 1<br>09:00 - 12:00"><span>Recitazione 04/22<br>Teacher 1<br></span></div>
    </div>
    <!-- 12:00-15:00 时间段 -->
    <div style="display:flex; gap:1px;">
        <div style="height: 48px; flex: 1 1 0%; background-color: rgb(221, 126, 107); color: rgb(102, 102, 102); border-radius: 3px; display: flex; align-items: center; justify-content: center; overflow: hidden; padding: 0px 5px; cursor: pointer;" class="mod-lezione c340 d35971" data-toggle="tooltip" data-placement="top" data-id="340" data-cal-id="141507" data-html="true" title="" data-original-title="Recitazione 04/22<br>Teacher 3<br>12:00 - 15:00"><span>Recitazione 04/22<br>Teacher 3<br></span></div>
    </div>
    <!-- 16:00-19:00 时间段 -->
    <div style="display:flex; gap:1px;">
        <div style="height: 48px; flex: 1 1 0%; background-color: rgb(230, 145, 56); color: rgb(0, 0, 0); border-radius: 3px; display: flex; align-items: center; justify-content: center; overflow: hidden; padding: 0px 5px; cursor: pointer;" class="mod-lezione c407 d35989" data-toggle="tooltip" data-placement="top" data-id="407" data-cal-id="132084" data-html="true" title="" data-original-title="Event Manager Nov 2022<br>Teacher 2<br>16:00 - 19:00"><span>Event Manager Nov 2022<br>Teacher 2<br></span></div>
    </div>
</div>

关键修改说明

  • 外层容器添加flex-direction: column,让各个时间段分组垂直堆叠,用gap控制分组间的垂直间距
  • 每个时间段的事件都放在独立的横向Flex容器中,这样同一时间段的多个事件会自动横向并排,用子容器的gap控制事件间的水平间距
  • 移除了原代码中用来定位的margin-top,改用结构化布局实现位置控制,避免Flex布局的冲突

如果你的日历需要事件对应具体的时间轴位置(比如09:00的事件固定在顶部,16:00的事件固定在下方对应位置),那CSS Grid布局会更适合——可以按时间划分行,将事件通过grid-row定位到对应行。但如果只是需要「同时间段并排、不同时间段垂直排列」,上面的分组方案就能解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:00:59