Search code examples
htmlcsswidthmargin

Width percentage with margin and different nestings


In my webpage I have a left and a right part, they are not on the same nesting though. I want the left part to fill 25% of the page and the right part to fill the rest of the width.
Simply putting 75% isn't cutting it for me because the right part also needs a 30px right margin. A right padding won't work because my content and background-color overflows then.
Do you have an idea how to solve this?
The .left (blue) and .right(yellow) div should always perfectly meet each other and the .right needs to keep it's 30px right margin.

body {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  overflow: hidden;
}

.main {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  overflow: hidden;
  background-color: grey;
}

.left {
  position: absolute;
  top: 0;
  bottom: 0;
  padding-top: 0;
  padding-bottom: 0;
  left: 0;
  width: 25%;
  border-right: 1px solid #eeeeee;
  background-color: lightblue;
}

.right {
  position: absolute;
  width: 75%;
  right: 0px;
  top: 45px;
  bottom: 0;
  /*padding-right: 30px;*/
  margin-right: 30px;
  background-color: yellow;
}
<body>
  <div class="main">
    <div class="left">TEST</div>
  </div>
  <div class="right">TEST</div>
</body>


Solution

  • It's not a good idea to create a layout using only absolute position. You may better rely on flexbox for example:

    body {
      height: 100vh;
      margin: 0;
      display: flex;
      background: grey;
    }
    
    .left {
      flex: 1;
      border-right: 1px solid #eeeeee;
      background-color: lightblue;
    }
    
    .right {
      flex: 4;
      margin-top: 45px;
      margin-right: 30px;
      background-color: yellow;
    }
    <div class="left">TEST</div>
    <div class="right">TEST</div>

    But in case you want to keep your code, you need to consider the margin within the calculation of the width:

    body {
      display: block;
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      bottom: 0;
      overflow: hidden;
    }
    
    .main {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      overflow: hidden;
      background-color: grey;
    }
    
    .left {
      position: absolute;
      top: 0;
      bottom: 0;
      padding-top: 0;
      padding-bottom: 0;
      left: 0;
      width: 25%;
      border-right: 1px solid #eeeeee;
      background-color: lightblue;
    }
    
    .right {
      position: absolute;
      width: calc(75% - 30px);
      right: 0px;
      top: 45px;
      bottom: 0;
      /*padding-right: 30px;*/
      margin-right: 30px;
      background-color: yellow;
    }
    <body>
      <div class="main">
        <div class="left">TEST</div>
      </div>
      <div class="right">TEST</div>
    </body>