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>