I'm trying to generate a simple gantt chart with html and css and I'm need to figure out how to make it compact, meaning if there is whitespace available the bar should try to fit in a previous row while maintaining the same x distance.
Context:
Current Output:

Desired Output:

Constraints
Current Implementation Snippet: [Edit] I've slightly changed the snippet to demonstrate the need for fixed distance from 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>
Other solutions I've tried:
Originally I started by rendering in JS a monthly matrix of squares and appending an element for each matching month and then using some convoluted logic to help the rendering but I realized it kept getting more and more complex so I backtracked to check if I was absolutely sure there was no simpler solution.
In the end the ultimate solution was to use css-grid by having a container with the following CSS:
.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
}
And each child element with the following CSS:
.timeline_item {
grid-column: 3 / 5; // defines start and end column where the item
}
So the following HTML would render exactly the way I needed it to:
<div class='timeline_container'>
<div class='timeline_item'></div>
<div class='timeline_item'></div>
<div class='timeline_item'></div>
</div>
I've written a more detailed article about the solution: https://www.cvtimeline.com/creating-a-gantt-timeline-with-css-grid/
css-grid rocks!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With