CSS Box Model

CSS Box Model

ยท

2 min read

The CSS box model is a way of representing the layout of HTML elements on a web page. It consists of the following parts:

  1. Margins: The space outside of the element's border

  2. Borders: A border around the element

  3. Padding: The space between the element's content and its border

  4. Content: The actual content of the element

About Box Model

In HTML, every element creates a box. Some of these elements, such as span, p, h1, etc are inline, meaning they are in line with the text, rather than structural elements of the page.

Other elements, like div, are large 'block' elements. Each element carries a different type, so getting familiar with these is useful when learning both HTML and CSS.

Block elements have a fixed width and height which sometimes span the entire page, while inline elements are within lines of text, meaning they have content floating beside them. Another type of element which is often used is an inline-block, which is simply a block of fixed width and height, within an inline context, such as within a block of text.

Regardless of whether an element is inline or a block, all elements have a number of core 'box' attributes. Those are shown in the image below.

How the CSS Box Model Works

Box Model Properties

We have 5 main properties, all of which can be defined separately. Below is a div with all the box model properties applied to it:

div {
  width: 300px;
  height: 200px;
  border: 1px solid black;
  padding: 10px;
  margin: 20px;
}

In this example, the div element would have a width of 300 pixels, a height of 200 pixels, and a border of 1 pixel solid black. The padding would be 10 pixels on all sides, and the margin would be 20 pixels on all sides.

You can control the appearance of an element using the properties of the box model, such as setting the width, height, and padding of an element, as well as specifying its margins and borders.

Thanks for reading ...

I hope this will help you in your CSS journey ๐Ÿ‘๐Ÿ‘

Did you find this article valuable?

Support Rohan Malo by becoming a sponsor. Any amount is appreciated!

ย