javascript - CSS 简单甘特图(紧凑)
问题描述
我正在尝试使用 html 和 css 生成一个简单的甘特图,我需要弄清楚如何使其紧凑,这意味着如果有可用的空白,则该栏应尝试适应前一行,同时保持相同的 x 距离.
语境:
- X 轴是以月为单位的时间线
- 每个项目在给定月份开始和结束
- 通过 JS 为每个元素生成宽度和边距
约束
- JS 解决方案是可以的,但理想情况下,该解决方案不需要使用过度杀伤的现有 js 库,因为代码将在浏览器扩展上运行,这会暴露很多兼容性问题。
- 这些项目不需要动态移动,因为在大多数情况下这将类似于渲染图像。
- 将呈现不超过 30 个项目。
当前实现片段: [编辑] 我稍微更改了片段以证明需要与 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 中渲染每月的正方形矩阵,并为每个匹配的月份添加一个元素,然后使用一些复杂的逻辑来帮助渲染,但我意识到它变得越来越复杂,所以我回溯以检查我是否绝对确定没有更简单的解决方案。
解决方案
最后,最终的解决方案是通过使用具有以下 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网格岩石!
推荐阅读
- mysql - mysql - 同一行更新查询发生死锁
- python - Python - 数组长度必须相同
- reportgenerator - ReportGenerator HtmlChart 报表输出使用
- linux - 使用 Socat (Linux) 的虚拟串行端口并允许缓冲区溢出
- r - 将字符串转换为R中的列表
- r - 如果任何列包含值列表,则进行变异
- node.js - 使用 Firebase Admin SDK 发送带有图像负载的推送通知
- python-3.x - 如何从集合中删除对象而不考虑顺序
- reactjs - 如何使用减速器在现有应用程序中添加反应管理员
- neo4j - Neo4j 和 Cypher