Home > Article > Web Front-end > How to achieve grid wrapping in CSS without media queries?
Grid Wrapping with CSS and Auto-Fill
Achieving grid wrapping in CSS without relying on media queries is possible through the use of auto-fill in the repeat() notation. The code snippet in the original question demonstrates a grid with explicit column widths, but to allow items to define their own widths, we can modify it as follows:
.grid { display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fill, min-content); } .grid > * { background-color: green; height: 200px; }
Auto-Fill
Auto-fill, as defined in the CSS Grid Layout specification, ensures that the number of repetitions in the repeat() notation is the largest possible value without causing the grid to overflow its container. This allows the grid to dynamically adjust the number of columns based on the width of its items.
In our case, we specify auto-fill as the repetition number and min-content as the fixed size for each column. Min-content ensures that each column is sized to fit its content, allowing the items to determine their own widths.
The result is a grid that will wrap its items without the need for media queries, effectively spacing them nicely even with a non-deterministic number of items.
The above is the detailed content of How to achieve grid wrapping in CSS without media queries?. For more information, please follow other related articles on the PHP Chinese website!