To make your layout work add this line of code:
* { box-sizing: border-box; }
jsFiddle demo
The box-sizing
property, and the difference between content-box
and border-box
.
Here's an illustration of the CSS box model:
With the box-sizing
property, you have two options for calculating the length of an element.
The property takes two values: content-box
and border-box
.
With content-box
(the default value), the length of the box – either width or height – includes only the content box. Neither the padding, border or margin are factored into the calculation.
In your code, the 25%-width boxes are wrapping because the 25% is applying only to the content section. But you also have a 2px border around each element. This means that the width of each box is actually: 25% + 4px. Multiply that by four and you have:
25% + 25% + 25% + 25% + 4px + 4px + 4px + 4px = 100% + 16px > 100% = wrapping
To counter this effect, CSS offers a second method for calculating length: box-sizing: border-box
.
With border-box
the calculation includes the content, padding and border. Hence:
25% + 25% + 25% + 25% + 4px + 4px + 4px + 4px = 100% (4px is factored into the 25%)
Further reading:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…