cssbrowserzoomingscaling

How to use relative CSS dimensions (%, vw, vh) and preserve user zooming/scaling


I have coded a website and have used a percentage width like so:

max-width: 50%

When the user zooms the website, the text and other divs are scaling OK but these percentage-set divs are enlarging very slowly. It feels like the origin of the %, which is the body, doesn't actually change its size value behind the scene too much, so things are not scaling proportionally.

Is there any way to keep using % or vw (viewport width) values and allow for good scaling?

I had to create way too many media queries and use px values to solve this issue:

  @media (min-width: 860px) {
    max-width: 400px;
  }
  @media (min-width: 1200px) {
    max-width: 600px;
  }
  @media (min-width: 1500px) {
    max-width: 600px;
  }
  @media (min-width: 1800px) {
    max-width: 600px;
  }
  @media (min-width: 2100px) {
    max-width: 600px;
  }

I have tried the %, but it didn't work.

px values scale well, but I have to create much more code, and it's also not scaling fluently.


Solution

  • I don't understand why you need so many media queries. But have you tried clamp? I think it would help you.

    .container {
        max-width: clamp(300px, 50%, 600px);
        background-color: blue;
        height: 200px; /* just to make it visible */
    }
    <div class="container"></div>

    This will make sure the container is never smaller than 300px, never larger than 600px, and will otherwise scale flexibly with 50% width. Just make sure clamp is supported.

    You can find more here about how clamp behaves.