Search code examples
cssresponsive-designwidth

Is there something equivalent to an "initial width" in css


I would like to set the width on a div so that when it initially displays, it would be set to some fixed value, which I would call the "initial width". If the user resizes their browser to make the width smaller, I would like the div's width to grow smaller but only to a minimum width (which can be set with min-width). I can't use the width rule to set the initial width because that keeps it fixed at that width even when the browser width gets smaller.


Solution

  • Sure, just use max-width and it won't expand beyond a certain width:

    element {
      max-width: 450px; /* 'initial width' */
      width: 100%;
      min-width: 100px; /* 'minimum width' */
    }
    

    Example:

    .resizeable {
      height: 150px;
      width: 500px;
      background: lightgrey;
      padding: 5px;
      border: 2px solid black;
      resize: horizontal;
      overflow: auto;
    }
    
    .element {
      height: 100px;
      max-width: 350px;
      width: 100%;
      min-width: 100px;
      background-color: grey;
      border: 2px solid blue;
    }
    <div class="resizeable"> Resize me!
      <div class="element">
        content
      </div>
    </div>