Reputation: 10585
I am new to CSS grid and am not sure whether it is possible to accomplish the following without resorting to using JavaScript.
I am trying to hide a sidebar when it will be less than 200px
wide.
But I only want to show a sidebar when 200px
is no more than 40%
of the available width.
.grid {
display: grid;
grid-template-columns: minmax(0, 200px) 1fr 0; /* what goes here ? */
min-height: 100px;
}
.grid .sidebar {
grid-area: 2 / 1 / 2 / 1;
background: red;
}
.grid .main {
grid-area: 2 / 2 / 2 / 2;
background: blue;
}
<div class="grid">
<div class="sidebar"></div>
<div class="main"></div>
</div>
For instance, let's say .grid
is 400px
wide. Then 40%
of 400px
is 160px
, but 200px
is more than 160px
, so .sidebar
should either not display or have 0
width.
But if .grid
is 1000px
wide, then 40%
of 1000px
is 400px
. Since 200px
is less than 400px
, it should display with width of 400px
.
Is this possible to do with just CSS grid, a combination of CSS grid and other CSS directives, or not possible without JavaScript?
Upvotes: 3
Views: 2766
Reputation: 12068
You can do something like this, if I understand you correctly and this is what you are after:
body {margin: 0} /* recommended */
.grid {
display: grid;
grid-template-columns: minmax(auto, 40%) 1fr; /* first column no more than 40%, ever (from 500px up) */
min-height: 100px;
}
.grid .sidebar {
/*grid-area: 2 / 1 / 2 / 1;*/
background: red;
}
.grid .main {
/*grid-area: 2 / 2 / 2 / 2;*/
background: blue;
}
@media (max-width: 499.99px) { /* screen width (or the .grid) needs to be at least 500px wide, in order to display the .sidebar, because min-width of 200px is exactly 40% of 500px, so display it when 500px and more, but hide it when less */
.grid {grid-template-columns: 1fr}
.grid .sidebar {display: none}
}
<div class="grid">
<div class="sidebar"></div>
<div class="main"></div>
</div>
Upvotes: 3