How can I pick one of two image sizes using CSS functions, not media queries?

Viewed 20

I have the following CSS, which produces a side-scrolling gallery of images that fits one image to screen width at viewports of up to 500px, and two above that. How can I rewrite it to use CSS functions instead of media queries? I've looked at MDN's documentation for min(), max(), and clamp() and it's really confusing how to do anything beyond the specified examples, which themselves are confusing. ("Think of the min() value as providing the maximum value a property can have.")

@media (min-width: 501px) {
  img { width: 48vw; }
}

@media (max-width: 500px) {
  img { width: 96vw; }
}

body { margin: 0; }

ul {
  margin: 2vw;
  padding: 0;
  display: flex;
  overflow-x: scroll;
  list-style-type: none;
}
<ul>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
</ul>

1 Answers

You can do it like below:

body { margin: 0; }

ul {
  margin: 2vw;
  padding: 0;
  display: flex;
  overflow-x: scroll;
  list-style-type: none;
}

img {
  width:clamp(48vw,calc(100vw - 500px)*-999,96vw);
}
<ul>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
</ul>

For more detail, check my article: https://css-tricks.com/responsive-layouts-fewer-media-queries/ where you will find a lot of tricks without media query including the above one

You can also do like below:

body { margin: 0; }

ul {
  margin: 2vw;
  padding: 0;
  display: grid;
  grid-auto-flow:column;
  grid-auto-columns: clamp(50%,calc(100vw - 500px)*-999,100%);
  overflow-x: scroll;
  list-style-type: none;
}

img {
  max-width:100%;
}
<ul>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
  <li><img src=http://placekitten.com/1280/960>
</ul>

Related