17. Box sizing

We can define the total width or height of an element counting or ignoring its border or padding.

box-sizing

Any border or padding is added to the total width of the element. It is the default style if not defined.

.elemento {
    box-sizing: content-box;
}

To fix this mismatch we can use border-box. The widths of the border or padding are subtracted, respecting the indicated width.

.elemento {
    box-sizing: border-box;
}

In the following example we can see an element that exceeds the desired measurement of 10rem in width.

.elemento {
    width: 10rem;
    padding: 2rem;
    border: 1rem solid black;
}
Lorem, ipsum dolor sit amet consectetur adipisicing elit.

How wide is it? width 10rem + 4rem padding (both right and left have 2rem) + 2rem border (both right and left have 1rem). In total 16rem, or 256px.

On the other hand, if we use box-sizing: border-box it does adjust.

.elemento {
    box-sizing: border-box;
    width: 10rem;
    padding: 2rem;
    border: 1rem solid black;
}
Lorem, ipsum dolor sit amet consectetur adipisicing elit.

It measures 10rem in total, or 160px. Measure it yourself with the Inspector!

More information

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.

Buy the book

Help me keep writing

Every coffee gives me a push toward the next article.

Comments

There are no comments yet.