Search code examples
javascripthtmlcsswidth

How to combine a min-width with a max-width that equals to 100% if needed in CSS?


I'm looking for CSS rules that allow setting fixed element width (let's say width: 500px), but combines it with max-width: 100% if a container is narrower than the element.

I'm thinking about something similar to:

.elem {
 width: 600px;
 max-width: 100%;
}

This snippet works perfect - if a .elem's container is narrower than the .elem itself, the .elem has container's width - smaller than 600px.

How to achieve the same effect with min-width? The following snippet doesn't work:

.elem {
 min-width: 600px;
 max-width: 100%;
}

Maybe any ideas using CSS Grid or even JavaScript?


Solution

  • Its seems like clamp(MIN, VAL, MAX) is your answer in this case. The clamp() CSS function clamps a value between an upper and lower bound. clamp() enables selecting a middle value within a range of values between a defined minimum and maximum. It takes three parameters: a minimum value, a preferred value, and a maximum allowed value. The clamp() function can be used anywhere a length, frequency, angle, time, percentage, number, or integer is allowed.

    clamp(MIN, VAL, MAX) is resolved as max()(MIN, min()(VAL, MAX))

    https://developer.mozilla.org/en-US/docs/Web/CSS/clamp()