Reputation: 77
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?
Upvotes: 2
Views: 3202
Reputation: 105853
Are you looking for someting alike :
body {
margin: 0;
}
div {
/* demo purpose */
width: 90%;
margin: auto;
padding: 1em;
border: solid;
/* flex optionnal */
display: flex;
flex-wrap: wrap;
gap: 1em;
}
button {
min-width: clamp(320px, 600px, 100%);
}
<div class>
<button>hello</button>
<button> hello hello hello</button>
<button> hello hello hello hello hello hello hello hello hello hello hello hello</button>
</div>
320px (can be 0 to X ) is the min-width you agree width, 600px the max-width you allow and 100% the limit not to pass.
here is a pen to test and play with : https://codepen.io/gc-nomade/pen/bGqyJmL
Upvotes: 3
Reputation: 71
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()
Upvotes: 2
Reputation: 743
min-width
cannot overwrite width
in your written code, I think same as @dantheman. you might looking for width: 100%; max-width: 600px min-width: 320px
.
It will take the whole container but not higher than 600px and not smaller than 320px.
Upvotes: 1