Calc of max, or max of calc in CSS

前端 未结 8 2472
小蘑菇
小蘑菇 2020-11-28 06:18

Is it possible to do something like this

max-width: calc(max(500px, 100% - 80px))

or

max-width: max(500px, calc(100% - 80px         


        
相关标签:
8条回答
  • 2020-11-28 06:20

    A workaround would be to use width itself.

    max-width: 500px;
    width: calc(100% - 80px);
    
    0 讨论(0)
  • 2020-11-28 06:23

    Change max to Max, you will see the dirty magic

    max-width: Max(500px, calc(100% - 80px)))
    
    0 讨论(0)
  • 2020-11-28 06:24

    min(), max(), and clamp() are finally available!

    Starting in Firefox 75, Chrome 79, and Safari 11.1 (except clamp).

    min() and max() take any number of arguments.

    clamp() has syntax clamp(MIN, VAL, MAX) and is equivalent to max(MIN, min(VAL, MAX)).

    min() and max() may be nested. They can be used in calc() as well as outside of it, they also may contain math expressions, that means you can avoid calc() when using them.

    Therefore the original example can be written as:

    max-width: max(500px, 100% - 80px);
    
    0 讨论(0)
  • 2020-11-28 06:28

    @Amaud Is there an alternative in order to have the same result ?

    There is a non-js pure css approach that would achieve similar results. You would need to adjust the parent elements container padding/margin.

    .parent {
        padding: 0 50px 0 0;
        width: calc(50%-50px);
        background-color: #000;
    }
    
    .parent .child {
        max-width:100%;
        height:50px;
        background-color: #999;
    }
    <div class="parent">
      <div class="child"></div>
    </div>

    0 讨论(0)
  • 2020-11-28 06:28

    This is only supported in dart-sass https://sass-lang.com/documentation/syntax/special-functions#min-and-max.

    You can also make use of string interpolation (similar to CSS variables) for this to work outside of dart-sass

    max-width: #{"max(500px, calc(100% - 80px))"}
    
    0 讨论(0)
  • 2020-11-28 06:31

    A 'pure' css solution actually is possible now using media queries:

    .yourselector {
      max-width: calc(100% - 80px);
    }
    
    @media screen and (max-width: 500px) {
      .yourselector {
        max-width: 500px;
      }
    }
    
    0 讨论(0)
提交回复
热议问题