The CSS Book

How the CSS Box Model works

The CSS Box Model views each HTML element as a box made up of content, padding and border. Margin is used to separate boxes. The purpose of the CSS Box model is to describe how width and height get shared between the content, padding and border of a box.

HTML

<body>
    <div class="box-model">CONTENT</div>
</body>

CSS

* {
    padding: 0;
    margin: 0;
}

.box-model {
    padding: 10px;
    border: solid 2px red;
    margin: 5px;
    width: 100px;
    height: 50px;
    /* box-sizing: content-box; */    
    /* box-sizing: border-box; */    
}

When box-sizing: content-box; is uncommented:

  • content width is 100px, content height is 50px

  • padding width is 10px, padding height is 10px

  • border width is 2px, border height is 2px

  • box width is 124px, border height is 74px

When box-sizing: border-box; is uncommented:

  • content width is 76px, content height is 26px

  • padding width is 20px, padding height is 20px

  • border width is 4px, border height is 4px

  • box-width is 100px, box height is 50px

How to position child elements absolutely in a parent element

<div class="holder">
  <h1>Merry Boxing Day</h1>
  <div class="date">Dec 26th 2018</div>
</div>
.holder {
  background-color: yellow;
  position: relative;
}

.date {
  position: absolute;
  top: 10px;
  right: 30px;
}

Last updated