Search code examples
cssresponsive-designcss-positionfixed

HTML CSS reserve width of a fixed div


i have a flex container that contains 2 divs, one of them is fixed, I want the other one to act just like its not fixed ( respect its width ), how to do that ?

<div class="container">
   <div style="position:fixed; width:15%;">...</div>
   <div style="width:85%">...</div> // starts from the beginning of the page and ignores the width of the upper div becuase its fixed
</div>


Solution

  • Layout wise there is no reason to put something fixed inside flexbox. Usual design pattern would be to use padding to offset things so that they wouldnt be covered by fixed position element with known dimensions.

    That said solution to what you are asking without using padding would be to wrap you fixed element in dummy element with correct size.

    html, body {padding: 0; margin: 0}
    
    .container {
      height: 2000px;
      display: flex;
    }
    
    .element-fixed {
      position: fixed;
      background-color: red;
      width: 15%;
    }
    
    .element1 {
      height: 300px;
      flex: 0 0 15%;
    }
    
    .element2 {
      height: 200px;
      background-color: blue;
      flex: 0 0 85%;
    }
    <div class="container">
       <div class='element1'>
          <div class="element-fixed">...</div>
       </div>
       <div class='element2'>...</div>
    </div>

    But here is a lot easier way to do it with padding.

    html, body {margin: 0; padding: 0;}
    
    .container {
      padding-left: 15%;
      display: flex;
      height: 2000px;
    }
    
    .fixed {
      position: fixed;
      background-color: red;
      height: 200px;
      width: 15%;
      margin-top: 10px;
    }
    
    .element1 {
      flex: 0 0 100%;
      background-color: blue;
      height: 200px;
    }
    <div class="fixed">...</div>
    <div class="container">
    
      <div class="element1">...</div>
    </div>

    Also position: sticky; can be something you might want to look into depending on what you are trying to do.