min/max width/height with multiple values

前端 未结 5 1141
执笔经年
执笔经年 2021-01-01 11:56

Edit in 2020 (min, max, clamp functions)

To anyone who get here by search engines:

CSS min / max / clamp functions had got some supports in recent (2020) bro

相关标签:
5条回答
  • 2021-01-01 12:25

    create separate classes and add them dynamically based on outerWidth()

    .some_element {
            background: red;
            float: left;
            width: auto;
        }
    
        .widthClass1{
         max-width:50%;
        }
    
        .widthClass2{
         max-width:200px;
        }
    
    
        $(document).ready(function(){
           if($("textDiv").outerWidth()<400){//instead of dividing by 2 I am comparing with 400
             $("textDiv").addClass('widthClass1')
           }else{
             $("textDiv").addClass('widthClass2')
           }
        });
    
    0 讨论(0)
  • 2021-01-01 12:32
    <div id="parent">
        <div id="sub">test content</div>
    </div>
    

    // css

    #parent {
        max-width: 200px;
    }
    #sub {
        width: 50%;
    }
    
    0 讨论(0)
  • 2021-01-01 12:33

    You can state this desired rule as 50% max width when the page width is less than or equal to 400px, and 200px when the page width is greater than or equal to 400px. That sounds a lot like a media query! I handle smaller screen widths first and then override for larger widths, which is this CSS:

    .some_element {
      background: red;
      float: left;
      width: auto;
      max-width: 50%;
    }
    @media (min-width: 400px) {
      .some_element {
        max-width: 200px;
      }
    }
    

    If you prefer, you can swap the 50% and the 200px and also change the min-width to max-width.

    0 讨论(0)
  • 2021-01-01 12:48

    You cannot set max-width to both 200px and 50%. You could put the element in another element with max-width of 400px:

    <div id="parent">
        <div id="child">Text here</div>
    </div>
    
    
    #parent {
        background-color: red;
        max-width: 400px;
    }
    #child {
        background-color: green;
        max-width: 50%;
    }
    
    0 讨论(0)
  • 2021-01-01 12:52

    You can try as mention below

    .some_element {
        background: red;
        float: left;
        width: auto;
        width: 50%; 
        max-width: 200px;        
    }
    
    0 讨论(0)
提交回复
热议问题