Search code examples
htmlcssclamp

css clamp function with auto not working as min, value, max


I have am using css clamp() to adjust height of my div, but it doesn't work as expected.

.container{
    height: clamp(200px, auto, 400px);
}

but works well when

.container{
    min-height: 200px;
    height: auto;
    max-height: 400px;
}

from the documentation css clamp(): MDN Web Docs , it says it does the job of min, value and max. why is it not working?


Solution

  • if you check the syntax you can see:

    clamp( <calc-sum>#{3} )
    where 
    <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*
    where 
    <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*
    where 
    <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
    

    auto is not a part of the syntax which is logical since you cannot compare auto with pixel value (or any length)

    You think that the browser will first apply auto to height in order to find the value of the height based on the content then convert that value to px and then apply the clamp() using that value but no. It doesn't work that way.

    The browser will try to first resolve clamp(200px, auto, 400px) which is invalid because auto is not a <calc-value>. We don't even need to know to which property its applied.