Box Model in CSS

Rahul Kumar
4 min readApr 6, 2023

--

Every Box contains of 4 parts:

  1. Content: It is actual content of element, like text or image.
  • Its size is known as content width and content height.
  • Browser by default calculate content height and width based on content itself but you can manipulate the the content size by CSS rule.

2. Padding: the padding extends the content size.

  • Its size is known as padding box width and padding box height.
  • Thickness of padding is known as padding top, padding bottom, padding left and padding right.

3. Border: The border goes around the padding and content.

  • Its size is known as border box width and border box height.
  • You can set different type of border. for e.g. solid, Dashed, Dotted, Double etc.
  • Calculate Border box width:
  • Calculate Border box height:
  • Border has three things size(optional), style and color(optional).
  • Border could be differnet styling like border top has some other style and border left is some other style.
border: dotted dashed;
/* top & bottom - dotted
left & right - dashed
*/

4. Margin: The margin extends the border area to separate the element from its neighboring elements .

  • margins are the outer space of the box / space between boxes.
  • Margins could be negative reduces gap between boxes.
  • It effects the layout and hence effects all the sibling.
  • Its size is known as Margin box width and margin box height.
  • CSS Rule to margin Size:
  • Calculate Margin Box width:
  • Calculate Margin Box height:
  • CSS Shorthand properties:

Note:

  • If you gave background-color to box then it includes to padding too but background-color will not apply on border and margin.
  • by default, box-sizing is content-box, that means whatever size, you would assign to that element and margin, padding, border, It includes everything in their width. So if you want to fix your width just change the box-sizing to border-box.
  • In border-box, whenever you will set value to width is some pixels so that will be fixed, it won’t change in changing the margin or anything.
  • Outline(box-shadow) won’t affect the layout.

Thanks:)

--

--

Rahul Kumar
Rahul Kumar

Written by Rahul Kumar

MERN Stack Developer building scalable web apps with MongoDB, Express.js, React, and Node.js. Sharing insights and best practices for modern web development.

No responses yet