CSS Box Model

What is Box Model in CSS?: Imagine each HTML element is surrounded by an invisible box. In the “CSS Box Model”, each HTML element has content, a border, padding, and margins. Let’s take a closer look at each one of these components.

CSS Box Model Property Block Diagram

Let’s see the diagram that illustrates the CSS Box Model Properties in detail.css box-model block diagram

The Content

The content is the information that the HTML element is made up of. For example, in a paragraph element, the content would be the text, whereas, in an image element, the content would be the picture.

 The Margin

The Margin is the area located above the border and the dimensions are the margin-box width and margin -box height. The Margin is used to specify elements separately.

The Padding

Padding is used to provide space between the content and the border. The dimensions of the padding are defined by the width and height od the padding box.

The Border

You can create borders around any HTML element on your web page. Simply use the border property and specify three values: “border-width”, “border-style”, and “border-color”, in that order. Border width can be specified in pixels. Some border-style values are solid, dashed, dotted, ridge, and none. The border-color property can take any CSS color value.

The Border Color Property Example

For example, if you want to add a solid blue border around your headers, you can use the following CSS code:

hl { border:2px solid blue;}
h2 ( border: solid blue; }

NOTE: You don’t have to specify all three values, so “solid blue” is allowed

To add Background Color and Border Example

We have already styled the color of the text and the fonts on your homepage. Now let’s try adding some borders. We will also add some background colors to make the borders easier to see. So, open your “styles.css” file and add two more declarations to your CSS code for the main header element: “background-color: yellow;” and “border:5px solid red;”. So the CSS code for your h1 element should look as follows:

h1 {
color: green;
font:bold 2em Tahoma;
background-color: yellow
border: 5px solid red;
}

Dotted Border Example

Now, let’s try out the dotted border. Add two more declarations to your CSS code for your p element:
“background-color pink,”, and “border:2px dotted purple;”.

Your CSS code for styling your paragraphs should look as follows:

P {
color:#6600FF;
font:1.4em Georgia;
background-color:pink;
border:2px dotted purple;
}

Ordered List Example

Finally, let’s try a dashed border. Add the following CSS code to style the ordered list element:

ol {
color:rgb(255,0,0);
background-color: #CCFF99;
border: 5px dashed blue;
} space

Now save the “styles.css” file. Next, open your “index.html” file and click “Run” on your Notepad++ taskbar to launch this file in Chrome or the browser of your choice.