I have a number of div
elements:
<main>
<div id="top">Top</div>
<div id="left">Left</div>
<div id="right">Right</div>
</main>
which I would like to show in a grid:
┌─────────────────┐
│ Top │
╞══════╤══════════╡
│ Left │ Right │
└──────┴──────────┘
I would like to be able to hide one element and have the other fill its space.
┌─────────────────┐
│ Top │
╞═════════════════╡
│ Right │
└─────────────────┘
The columns are not evenly spaced. I have used the following CSS for the main
and div#top
elements:
main {
display: grid;
grid-template-rows: 3em 1fr;
grid-template-columns: 120px 1fr;
border: medium solid #333;
}
div#top {
grid-column: 1/3;
}
The problem is that when I hide the first div
using display: none
, the second one only occupies the original space of the first one.
How can I convince the second div to take up the whole row?
The snippet below illustrates the point.
Note: The question at Make div fill up entire CSS grid's row when the other part is not available asks something similar, but solution doesn’t work in my case. This is because my Left div has a set width.
var left = document.querySelector('div#left');
var right = document.querySelector('div#right');
right.addEventListener('click', function(e) {
left.style.display = left.style.display == 'none' ? 'block' : 'none';
});
main {
display: grid;
grid-template-rows: 3em 1fr;
grid-template-columns: 120px 1fr;
border: medium solid #333;
}
div#top, div#left, div#right {
border: medium solid #999;
background-color: #f8f8f8;
margin: 4px;
font-family: sans-serif;
padding: .5em;
}
div#top {
grid-column: 1/3;
}
div#left {
}
div#right {
}
<main>
<div id="top">Top</div>
<div id="left">Left</div>
<div id="right">Right: Click to Toggle Left</div>
</main>