Search code examples
htmlcsscentering

How can I make to work padding, which is scaling by browser's width, when centered a content using `diplay: table;`?


^As title says^. I need to scale padding by a browser's width. I tried this:

html, body{
  height: 100%;
}

body{
  display: table;
  margin: 0 auto;
}

#center{
  display: table-cell;
  vertical-align: middle;
}

.box{
  padding: 25%;
  background: #000;
  color: white;
}

h1{
  margin: 0;
  padding: 0;
}
<div id="center">
  <div class="box">
    <h1>Hello world</h1>
  </div>
</div>

But it doesn't work. Is there any way I can do it? I want to center the div using display: table;, not using flexbox or position: absolute. Thanks.


Solution

  • Use vw which is percent of viewport width.

    html, body{
      height: 100%;
    }
    
    body{
      display: table;
      margin: 0 auto;
    }
    
    #center{
      display: table-cell;
      vertical-align: middle;
    }
    
    .box{
      padding: 5vw;
      background: #000;
      color: white;
    }
    
    h1{
      margin: 0;
      padding: 0;
    }
    <div id="center">
      <div class="box">
        <h1>Hello world</h1>
      </div>
    </div>

    See fiddle here you can resize the viewable area and see the padding size change.