Search code examples
csswidthoverlaymargin

How to get width 100% right in overlay with CSS


I am creating an overlay but the width ends up wrong on the right. Where do I go wrong? In the end I want some buttons that are 100% width of the screen, minus some margin.

body
{
   width: 100%;
   margin: 0px;
}

.a1 
{
  background-color: rgba(0, 0, 0, 0.7); 
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.a2 {
  width: 100%;
  border: 5px solid blue;
   }
  <div class="a1">
    <div class="a2">The width is going to far on the right</div>
  </div>


Solution

  • You don't need to specify width: 100% on the child div a2. As a block element, it will automatically fill the available width of the parent element, which is set at 100%.

    Your a2 CSS becomes:

    .a2 {
      border: 5px solid blue;
    }
    

    In this way your margins are respected and work as expected:

    * {
      box-sizing: border-box;
    }
    
    body
    {
       width: 100%;
       margin: 0px;
    }
    
    .a1 
    {
      background-color: rgba(0, 0, 0, 0.7); 
      position: fixed;
      width: 100%;
      height: 100%;
      z-index: 1;
    }
    
    .a2 {
      border: 5px solid blue;
    }
    <div class="a1">
      <div class="a2">The width is going to far on the right</div>
    </div>

    Following OP comment about sizing of elements

    I notice that you don't specifically mention that you are using border-box as your box-sizing methods. I have added this into the snippet now.

    Using border-box means that when you specify the size of a box, you are including the borders inside that size.

    For example, if the width is set to 100%, this is 100% including any borders you have on your elements. Most normalized stylesheets set box-sizing to border-box by default.