What is Box Model?
Every element that can be displayed on a web page is comprised of one or more rectangular boxes. CSS box model typically describes how these rectangular boxes are laid out on a web page. These boxes can have different properties and can interact with each other in different ways, but every box has a content area and optional surrounding padding, border, and margin areas.
The following diagram demonstrates how the width, height, padding, border, and margin CSS properties determines how much space an element can take on a web page.
Padding is the transparent space between the element’s content and its border (or edge of the box, if it has no border), whereas margin is the transparent space around the border.
Also, if an element has the background color it will be visible through its padding area. The margin area is always remain transparent, it is not affected by the element’s background color, however, it causes the background color of the parent element to be seen through it.
Width and Height of the Elements
Usually when you set the width and height of an element using the CSS
height properties, in reality you are only setting the width and height of the content area of that element. The actual width and height of the element’s box depends on the several factors.
The actual space that an element’s box might take on a web page is calculated like this:
width + padding-left + padding-right + border-left + border-right + margin-left + margin-right
height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom
You will learn about each of these CSS properties in detail in upcoming chapters.
Now let’s try out the following example to understand how the box model actually works:
padding: 15px; /* set padding for all four sides */
border: 10px solid black; /* set border for all four sides */
margin: 20px auto; /* set top and bottom margin to 20 pixels, and left and right margin to auto */
Note: In CSS box model; the content area of an element’s box is the area where its content, e.g., text, image, video, etc. appears. It may also contain descendant elements boxes.