Box Model in CSS
The actual width and height of the element can be determined by a number of properties:
- By the contents of the element.
2. The padding and border affect the width and height of the element. In a CSS box, the width and height can be calculated by the following formulas:
width = border-right + padding-right + width + padding-left + border-left
height = border-top + padding-top + height + padding-bottom + border-bottom
In this example, the a elements accept padding values on all sides. So the width and height of the elements not only include the font size of a, but also include the padding. (It is also worth noting that even the height of the inline elements become longer with padding, the vertical padding will not affect neighboring inline elements.)
3. Declare width and height properties. If the height you set is shorter than the top and bottom padding, browser will just go ahead to use the padding as the element’s height. For example:
We notice that the yellow background div is longer than the green one. This is because the yellow div takes the content height into account and also add the top and bottom padding as total height. In the green div, the height is set 30px , which is shorter than the combined top and bottom padding(20px + 20px). In this case, the browser will just ignore the declared height value and the content height inside as well — only use the padding as the element’s height.
4. By the display property. Block-level elements have a default width of 100% to take up the entire horizontal space. For inline elements, width and height can’t be applied and only occupy their own space.
In the first example on the left, height and width of the a element in box1 are just determined by the content “Item 1”. Since a elements are inline elements by default, they don’t take width and height. In comparison, I change the display property to inline-block in the second example, the height and width are now determined by the specified width and height in the CSS.
5. By the box-sizing property. Content-box is the default box-sizing value in CSS, so applying padding on it will actually make the element larger. Its actual width will not be the same with the specified width. However, applying border-box will make the total width as specified. This can be demonstrated by below example:
Notice that partial words got covered by the border in the border box? In order to achieve total width of 60px, the width of content inside the border-box got reduced to 30px. For content-box, the content width stays 60px and its box’s width becomes 90px(60 + 5*2 + 10*2).