16. 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

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.