I currently have a div style as a grid display. The grid-template-columns
are each 1/3 of the body. However, I would like to limit each box to a minimum width of, say, 200px
. This way, on mobile I won't have three extremely skinny boxes. Is there any way to do this, or am I approaching the problem in completely the wrong way?
.wrapper {
display: grid;
grid-template-columns: 33% 33% 33%;
grid-gap: 10px;
background-color: #fff;
color: #444;
}
.box {
background-color: #444;
border-color: #Dd6161;
border-style: solid;
border-width: 2px;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 14px;
}
If you really need the columns to be the exact same width you should use: grid-template-columns: repeat(3, minmax(0, 1fr)); minmax(0, 1fr) allows the grid tracks to be as small as 0 but as large as 1fr , creating columns that will stay equal.
With CSS Grid Layout, we get a new flexible unit: the Fr unit. Fr is a fractional unit and 1fr is for 1 part of the available space. The following are a few examples of the fr unit at work. The grid items in these examples are placed onto the grid with grid areas.
What's a fraction (1FR)? A fraction or 1FR is one part of the whole. 1 fraction is 100% of the available space. 2 fractions are 50% each. So, 1FR is 1/2 of the available space.
This might be what you're looking for if you only have three boxes in the wrapper and you want them to wrap onto another row if the wrapper is less than 600px.
.wrapper {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
What this does is:
repeat
- this just tells the gird to do the following multiple times.auto-fit
- this is the first argument inside the 'repeat' and
tells the grid to 'fit the columns in the grid by expanding them to
take the entire space of the grid. It also means if the items don't
fit in a single row they will wrap.minmax(200px, 1fr)
means
that each column in the grid will be a minimum of 200px and a max of an equal amount of space (so if there are three items, it will be 33.333% each).Here is an example: https://codepen.io/chrisboon27/pen/RMjGme
Alternately if you want them to all become full width (so one column of three rows) you would use grid-template-columns: repeat(3, minmax(200px, 1fr));
and then use a media query to change it to grid-template-columns: 1fr;
to make it a single column:
.wrapper {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(3, minmax(200px, 1fr));
}
@media (max-width: 600px){
.wrapper{
grid-template-columns: 1fr;
}
}
Here is an example of this one: https://codepen.io/chrisboon27/pen/pLdNjb
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