CSS: border-box, border, outline

The aim of this post is to see different methods to wrap a line/border around your element and understand how they affect the element’s dimensions.
I’ll compare three ways of adding a border around an element:

  • border and box-sizing:border-box,
  • border (in the default box model) and
  • outline:

<div style="width: 300px;">hello world</div><br>

<div style="outline:10px solid #006699; width: 300px;">hello world</div><br>

<div style="border:10px solid #006699; width: 300px;">hello world</div><br>

<div style="box-sizing: border-box; border:10px solid #006699; width: 300px;">hello world</div><br>



We can see that when using outline, the width and the position of the element doesn’t change. It draws a line around the element and doesn’t affect its dimensions.

An outline is a line that is drawn around elements outside the borders.
The outline is not a part of an element’s dimensions; the element’s total width and height is not affected by the width of the outline.

border in the default box model

When using a border in the default box model (box-sizing:content-box;), the width of the element is increased by its border size; the total width of the element becomes then 300px + 10px (left border) + 10px (right border).

border in the border-box model

When changing the box-sizing model to border-box and applying the same border, the total width of the element stays the width that you specified, in this case the width stays 300px. This is extremely useful when dealing with 100% widths. The reason for this is that in the default box model, if you have an element that has a 100% width and a border, the element will have the width of its parent + the border width (and thus exceed the parent’s width), which will be very inconvenient in most cases.
The border-box value (as opposed to the content-box default) makes the final rendered box the declared width, and any border and padding cut inside the box.

Post a Comment