With
grid-template-columns:1fr 1fr;
the 2 columns have different width in small(narrow) screen. I can not understand. Thank you for any help.
In the ideal case, the two cells will have the same size.
But every cell has a minimum size! It is defined as the minimum content width. For example: the larger word, the larger button, or the larget image that it contains.
To avoid this, you should use minmax(0, 1fr) for each column definition. It allows you to say that 1fr, one fraction, is the maximum width of the column.
To sum up, use this code:
.grid {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
Here is a live demo of the problem and solution.
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
}
.grid--fix {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
/* Demo styles */
.grid {
grid-gap: 20px;
max-width: 400px;
}
.cell {
background: hotpink;
text-align: center;
padding: 1em;
}
<p>Exact same cells</p>
<div class="grid">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2</div>
</div>
<p>The cells adapt their size to contain their content</p>
<div class="grid">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2 is biiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiig</div>
</div>
<p>This behaviour could be disabled with <code>minmax(0, 1fr)</code></p>
<div class="grid grid--fix">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2 is biiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiig</div>
</div>
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