Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcus-at-localhost/0917dddffede299ce1e90f4e30a74eda to your computer and use it in GitHub Desktop.
Save marcus-at-localhost/0917dddffede299ce1e90f4e30a74eda to your computer and use it in GitHub Desktop.
[Mind the Gap - CSS Grid Hide a Column] #css #grid #column

Mind the Gap - CSS Grid Hide a Column

Depending on how the CSS grid is set up, you can't just hide a column and reflow the rest of the grid. If the column has a fixed with, the space is preserved, if the column width is 0 after hiding the grid gap adds up. The only way to fix it is to reflect the changes in the grid template.

A Pen by Marcus Obst on CodePen.

License.

div
button hide .col2
hr
.flex
.col1
.col2
.col3
h1 Flexbox
.col4
pre: code
| .closed .flex .col2 {
| display:none;
| }
.grid
.col1
.col2
.col3
h1 CSS Grid
.col4
pre: code
| .closed .grid .col2 {
| display:none;
| }
.grid.fixed
.col1
.col2
.col3
h1 CSS Grid .fixed
.col4
pre: code
| .closed .grid .col2 {
| display:none;
| }
| .closed .grid.fixed {
| grid-template-areas: "col1 col3 col4";
| grid-template-columns: max-content 1fr 1fr;
| }
document.querySelector('button').addEventListener('click', (event) => {
document.querySelector('body').classList.toggle('closed');
});
.grid {
display: grid;
grid-template-columns: max-content max-content 1fr 1fr;
grid-template-rows: 30vh;
gap: 15px;
grid-template-areas: "col1 col2 col3 col4";
}
.flex{
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
height: 30vh;
gap:15px;
}
// Hide .col2
.closed .flex,
.closed .grid {
.col2 {
display:none;
}
}
.closed .grid.fixed {
grid-template-areas: "col1 col3 col4";
grid-template-columns: max-content 1fr 1fr;
}
.col1 { grid-area: col1; }
.col2 { grid-area: col2; }
.col3 { grid-area: col3; }
.col4 { grid-area: col4; }
.flex {
.col3, .col4 {
flex-grow: 1;
flex-shrink: 0;
flex-basis: 0px;
}
}
// demo styles
.flex,
.grid
{
&>div{
padding:15px;
&:before{
content: attr(class);
display:block;
}
}
}
.flex>div {
background-color: #ffc107;
}
.grid>div {
background-color: #f44336;
}
.fixed>div{
background-color: #4caf50;
}
// holiday.css css property @see https://holidaycss.js.org/
:root {
--max-body-width: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/holiday.css@0.9.5" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment