I have the following simple grid setup. It works as intended in situations where there are both content
and sidebar
divs present, but I would however like the content
area to expand to fill the area left by sidebar
when a sidebar
area is not present on the page. In the second grid in the example below, sidebar
is not present but the content
area does not expand to fill up the left over space. I would like it to do so.
/* Based on example from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas */
.content {
grid-area: main;
}
.sidebar {
grid-area: side;
}
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-areas:
"main side"
}
* {box-sizing: border-box;}
.wrapper {
border: 2px solid #f76707;
border-radius: 5px;
background-color: #fff4e6;
max-width: 940px;
margin: 0 auto 30px auto;
}
.wrapper > div {
border: 2px solid #ffa94d;
border-radius: 5px;
background-color: #ffd8a8;
padding: 1em;
color: #d9480f;
}
<!-- First grid - works fine -->
<div class="wrapper">
<div class="content">Content</div>
<div class="sidebar">Sidebar</div>
</div>
<!-- Second grid - content should expand to fill the area that would be used by sidebar -->
<div class="wrapper">
<div class="content">Content</div>
</div>
Perhaps this is a case where I shouldn't be using CSS grid for this, but rather floats?
If you don't have to use grid-area, flexbox gives intended result. No need to use float.
/* Based on example from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas */
.content {
flex-grow: 1;
}
.sidebar {
flex-grow: 1;
}
.wrapper {
display: flex;
}
* {box-sizing: border-box;}
.wrapper {
border: 2px solid #f76707;
border-radius: 5px;
background-color: #fff4e6;
max-width: 940px;
margin: 0 auto 30px auto;
}
.wrapper > div {
border: 2px solid #ffa94d;
border-radius: 5px;
background-color: #ffd8a8;
padding: 1em;
color: #d9480f;
}
<!-- First grid - works fine -->
<div class="wrapper">
<div class="content">Content</div>
<div class="sidebar">Sidebar</div>
</div>
<!-- Second grid - content should expand to fill the area that would be used by sidebar -->
<div class="wrapper">
<div class="content">Content</div>
</div>
You're wrapper contains two columns which are specified in:
grid-template-columns: 1fr 1fr;
Both columns are 1fr wide (1 fraction of a total of 2)
Deleting one of the divs inside will not expand the other since it is still 1 of two fractions wide.
Remove one of the columns in the grid will fix your issue:
grid-template-columns: 1fr;
As a sidenote, since your wrapper now only contains a single div inside it makes no sense for it to be a grid.
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