首页 > 解决方案 > CSS 简单甘特图(紧凑)

问题描述

我正在尝试使用 html 和 css 生成一个简单的甘特图,我需要弄清楚如何使其紧凑,这意味着如果有可用的空白,则该栏应尝试适应前一行,同时保持相同的 x 距离.

语境:

电流输出: 在此处输入图像描述

期望的输出: 在此处输入图像描述

约束

当前实现片段: [编辑] 我稍微更改了片段以证明需要与 x 固定距离。

.timeline div {
    height: 10px;
    background: black;
    margin: 2px;
}
<div class="timeline">
  <div style="width: 80px; margin-left: 0px;"></div>
  <div style="width: 40px; margin-left: 35px;"></div>
  <div style="width: 45px; margin-left: 40px;"></div>
  <div style="width: 100px; margin-left: 135px;"></div>
  <div style="width: 160px; margin-left: 270px;"></div>
  <div style="width: 185px; margin-left: 385px;"></div>
</div>

我尝试过的其他解决方案:

最初,我首先在 JS 中渲染每月的正方形矩阵,并为每个匹配的月份添加一个元素,然后使用一些复杂的逻辑来帮助渲染,但我意识到它变得越来越复杂,所以我回溯以检查我是否绝对确定没有更简单的解决方案。

标签: javascripthtmlcss

解决方案


最后,最终的解决方案是通过使用具有以下 CSS 的容器来使用 css-grid:

.timeline_container {
    display: inline-grid; // all contents of the container will be treated as grid elements
    grid-auto-columns: 40px; // defines the default width of each column
    grid-auto-rows: 40px; // defines the height of each row

    /* the line below is the key part to making it compact/dense */
    grid-auto-flow: row dense; // keeps rows compact by filling available row whitespace
}

并且每个子元素都具有以下 CSS:

.timeline_item {
    grid-column: 3 / 5; // defines start and end column where the item
}

因此,以下 HTML 将完全按照我需要的方式呈现:

<div class='timeline_container'>
    <div class='timeline_item'></div>
    <div class='timeline_item'></div>
    <div class='timeline_item'></div>
</div>

我写了一篇关于解决方案的更详细的文章:https ://www.cvtimeline.com/creating-a-gantt-timeline-with-css-grid/

CSS网格岩石!


推荐阅读