DEV Community

Poulami Chakraborty
Poulami Chakraborty

Posted on

CSS Box Model

CSS Box Model

Every element box has a content area which includes the content of the element, and optional surrounding padding, border, and margin areas.

The rendered content determines the height of the content box. The width is determined by the width of the parent element (block elements) or by rendered content (inline elements).

Watch Out For

  • Box-sizing: By default, the height & width is set to the content-area. Any border or padding will add to the width and height to arrive at the size of the box that's rendered on the screen. (Margin isn't included as a part of element's box-size).
div{
width: 300px;
padding: 10px;
margin: 0;
}

The above <div> will have a width of 320px (200px +60px (padding-left) + 60px(padding-right)). (This is why 4 divs with width:25% do not fit on the same row).In most (read almost all) cases, it’s much easier and feasible to specify the size of the whole box. To do that, set ‘box-sizing: border-box’ (Default is ‘box-sizing: content-box’).

  • Default values: Browsers may have elements may have default margins, paddings, etc. To avoid calculation mismatch due to those, you can reset those for all elements.
{ margin:0; padding:0; }
  • Margin-collapsing: The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal). Margin-collapsing occurs for siblings within a formatting context.

  • Anonymous boxes: An anonymous box is created when there is not an HTML element to use for the box. It will then behave as a inline item. But it cannot be targeted and styled like a regular box because there is no element to target. (including with .parent>*) - check if you have missed an HTML tag.

  • Content: Content is needed to set width, height, etc (content can be ""). For pseudo elements (:before:after), box isn't generated until content is specified.

Top comments (0)