There are some questions looked at here, but they don't quite solve the problem I'm looking for.
Suppose I have a website and I want to. On the desktop I want this:
It's easy. grid-template-columns: Repeat (3, 33%)
(Basically)
But, on a mobile device, I want this
What I encountered happened before it flipped to a single column:
I'm trying clamp()
, minmax()
and all kinds of stuff, but nothing is working the way I want. Yes, I could definitely use media queries, but I'd like to create a truly fluid grid/flex layout using modern CSS (like clamp, grid, minmax, etc.) so that no media queries are needed to make basic layout changes. < /p>
I know this doesn't work, but as a starting point for the request, here's a simple version of one of my 100 attempts :) In this version I try to switch from repeat(3) to repeat(1) using clamp ).
.wrapper { display: grid; gap: 15px; grid-template-columns: repeat(clamp(1, calc(100% - 500px), 3), 33%); } .one { background: red; } .two { background: green; } .three { background: blue; }
<div class="wrapper"> <div class="item one"><h3>Example A</h3></div> <div class="item two"><h3>Example Two</h3></div> <div class="item three"><h3>Third Example</h3></div> </div>
Full article with more general rules: https:// css-tricks.com/responsive-layouts-fewer-media-queries/
Here's an idea to use
max(0px, (400px - 100vw)*1000)
in flex-basis. If100vw
(screen size) is greater than400px
, this formula will give0px
, or in the opposite case a very large value for each element provides a bigflex-basis
and creates a wrapper. Just adjust400px
to play@media (max-width:400px)
Using CSS Grid, it can look like this:
A similar question where I control the maximum number of columns without media queries: CSS Grid - Maximum number of columns without media queries
We can extend the above solution to consider more complex cases.
Example of moving from 6 columns to 3 columns to 1 column:
To understand these values, consider the following ranges:
To get 6 columns we need values in the range
]14.3% 16.7%]
(I'm considering15%
) To get 3 columns we need values in the range]25% 33.3%]
(I was thinking30%
)We just avoid the edges to make sure we account for the gaps.
A more general solution using CSS variables, where I would add
0.1%
to ensure the value is large enough to get the desired number of columns and can accommodate the gaps.We also add some dynamic coloring (related: How to change the color of an element based on its height or width? )
Using flexbox we can have a different (possibly desired) behavior where the last item of a row will take up all available space: