Explaining CSS Box Model in Details...

Explaining CSS Box Model in Details...

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.

The following diagram illustrates how the CSS properties of padding, border and margin dictate that how much space an attribute will occupy on a web page.

box.png

The CSS box model contains the different properties in CSS. These are listed below.

  • Margin
  • Border
  • Padding
  • Content

Now, we are going to determine the properties one by one in detail.

Margin

This segment consists of the area between the boundary and the edge of the border. The proportion of the margin region is equal to the margin-box width and height. It is better to separate the product from its neighbor nodes. This property is a shorthand for the following CSS properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

Syntax

/* Apply to all four sides */
margin: 1em;
margin: -3px;

/* top and bottom | left and right */
margin: 5% auto;

/* top | left and right | bottom */
margin: 1em auto 2em;

/* top | right | bottom | left */
margin: 2px 1em 0 auto;

/* Global values */
margin: inherit;
margin: initial;
margin: revert;
margin: revert-layer;
margin: unset;

Border

It is a region between the padding-box and the margin. Its proportions are determined by the width and height of the boundary. This property is a shorthand for the following CSS properties:

  • border-color
  • border-style
  • border-width

Syntax

/* style */
border: solid;

/* width | style */
border: 2px dotted;

/* style | color */
border: outset #f33;

/* width | style | color */
border: medium dashed green;

/* Global values */
border: inherit;
border: initial;
border: revert;
border: revert-layer;
border: unset;

Padding

This field requires the padding of the component. In essence, this area is the space around the subject area and inside the border-box. The height and the width of the padding box decide its proportions. This property is a shorthand for the following CSS properties:

  • padding-bottom
  • padding-left
  • padding-right
  • padding-top

Syntax

/* Apply to all four sides */
padding: 1em;

/* top and bottom | left and right */
padding: 5% 10%;

/* top | left and right | bottom */
padding: 1em 2em 2em;

/* top | right | bottom | left */
padding: 5px 1em 0 2em;

/* Global values */
padding: inherit;
padding: initial;
padding: revert;
padding: revert-layer;
padding: unset;

Content

Material such as text, photographs, or other digital media is included in this area. It is constrained by the information edge, and its proportions are dictated by the width and height of the content enclosure.

Thank You for Reading

Source - MDN & JAVAPOINT