Given the following layout:
<div id="grid" style="display: grid; grid-template-columns: min-content auto; width: 100px; height: 100px; border: 1px solid #ccc;">
<div id="first" style="width: 20px; background-color: green;">
</div>
<div style="background-color: cyan;">
</div>
</div>
I want to toggle visibility of the "first" child so the second one will occupy the remaining space.
The grid seems to be doing a silly thing by re-assigning the hidden column definition to the next visible one, so after hiding the first child the second one becomes "the first" as far as the grid layout sees it and it inherently uses "auto". Since there’s no content in the child child it just doesn’t display anything. I’d expect grid-template-columns to stick regardless of the actual columns visibility.
If the child would got physically removed from the grid the latter would be in its full right to do that, but I’m only changing the visibility.
Needing to manage grid-template-columns for such a scenario creates a totally unnecessary overhead in my opinion, I’d appreciate if people can share their thoughts on it.
I’m aware of the fact that some layouts for example those which use repeat(...)
may not suffer form the issue, but I’m looking for a fix just for my scenario.
2
Answers
You can give
grid-column: span 2;
to an element so that it takes up its own space + the space of the element that receivesdisplay: none;
:If you want to toggle the visibility of the "first" child while keeping the second child in its original position and size, you can achieve this by modifying the CSS. One way to do it is by setting a fixed width for the first column, so it doesn’t change when you hide the first child.
Here’s an example:
The first column is given a fixed width of 20px, which ensures that it doesn’t change when you hide the "first" child. The second column still takes up the remaining space, as specified by "auto."
This approach avoids the need to manage grid-template-columns dynamically when toggling visibility, as the column widths are explicitly defined.