Using CSS Grid layout how can I safely hide a row without grid-template-rows layout properties getting passed over to the next row? I tried display: none; but the layout of the hidden element is passed over to the next element.
Here's a code example: http://plnkr.co/edit/E3kuJcDxKnrjjbdVHQbO?p=preview. What I'm trying to do is toggle the visibility of the .item2 element without effecting any other elements on the page. Thanks!
You can achieve this by setting that row's height to 0 via the grid-template-rows declaration, and then setting the visibility of the element you want to hide to hidden.
Assuming you want to hide the second row:
.grid-hiderows {
grid-template-rows: auto 0px;
}
.grid-hiderows .item:nth-child(2) {
visibility: hidden;
}
Similarly, to hide the third row:
.grid-hiderows {
grid-template-rows: auto auto 0px;
}
.grid-hiderows .item:nth-child(3) {
visibility: hidden;
}
If you need your grid to utilize a gap between columns / rows, you won't be able to use the gap property when using this method. You'd instead need to resort to some negative margin manipulation to handle the extra gap space.
<div class="grid">
<div class="item item-fullwidth">1</div>
<div class="item item-fullwidth" data-hideme>
<img src="https://via.placeholder.com/600x150/5eba7d/FFFFFF?text=Row+2" style="width: 100%;height: auto;display:block;"></div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
<button data-toggle style="margin-top:1em">Toggle hidden row</button>
<style>
:root {
--gap: .5em;
--rowHeight: auto;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-auto-rows: var(--rowHeight); /* Or use grid-template-rows if row heights will need to be varied / manually set */
}
.item {
box-shadow: inset 0 0 0 1px lightgray;
padding: .5em;
}
.item-fullwidth {
grid-column: span 4;
}
[data-hideme] {
padding: 0;
}
/**
*
* Define toggled state
* @ change the appropriate row's height on the parent grid to 0 via `grid-template-rows`
* @ change the element to hide's visibility to 'hidden'
*
**/
.grid-hiderows {
grid-template-rows: var(--rowHeight) 0;
}
.grid-hiderows [data-hideme] {
visibility: hidden;
}
/**
*
* Allow for gaps between rows / columns
*
**/
.grid {
margin-left: calc(var(--gap)/-2);
margin-right: calc(var(--gap)/-2);
}
.item {
margin-right: calc(var(--gap)/2);
margin-left: calc(var(--gap)/2);
}
.item + .item {
margin-top: var(--gap);
}
</style>
<script>
document.querySelector('[data-toggle]').onclick = function() {
document.querySelector('.grid').classList.toggle("grid-hiderows");
};
</script>
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