HTML

CSS Box Model

Programmingempire

In this example, I will explain CSS Box Model. Basically CSS Box Model is an essential element a design. Also, we frequently use it in web page layout. The following figure represents the Box Model.

Illustration of CSS Box Model
Illustration of CSS Box Model

Components of CSS Box Model

As can be seen in the above figure, the Box Model comprises of following elements.

  • Margin
  • Padding
  • Border
  • Content

Since, the box model is applicable to any container element, we can use the CSS properties of margin, padding, and border on containers. While content may represent any text, images, hyperlinks. Also, content can include other HTML elements including containers. Similarly border represents a border enclosing the content. Further, the padding is the space between content and its borders. Whereas margin is the space between the border and other HTML elements. Furthermore, the values of margin and padding may be different on each side of the content. The following example illustrates the concept of CSS Box Model.

Example

<html>
 <head>
   <title>Box Model Example</title>
   <style>
     body{
	margin: 20px;
	text-align: center;
     }
     .mydiv{
        background: #ffaa99;
	font-size: 20px;

        /* Box Properties */
	width: 560px;
        height: 450px;
        border: 10px solid #551199;
	margin: 100px;
        padding: 50px;
     }
   </style>
 </head>
 <body>
    <h1>CSS Box Model</h1>
    <div class="mydiv">
      This is an example demonstrating Box Properties of CSS.
    </div>
 </body>
</html>

Output

An Example Illustrating CSS Box Model
An Example Illustrating CSS Box Model

As can be seen in the example code, the document contains a DIV element. Basically, the CSS class mydiv contains Box properties. We apply these properies on the DIV element using the class attribute. Further, the box in this example contains the DIV element, its border, margin, and padding. Also, the corresponding box properties are margin, padding, border, width, and height. Hence, we can compute the box size as follows. The width of box includes left and right margin, left and right padding, border width, and width of DIV element. So the box width is 100px+100px+50px+50px+10px+10px+560px. That equals 880px. Similarly, we can compute height of the Box. So, the box height is 100px+100px+50px+50px+10px+10px+450px. Hence we get 770px as the height of the Box.

In fact, box properties paly a significant role in designing the layout of the web page. With the help of computing box dimensions we can correctly place HTML elements on the page. Since we can determine how much size a particular element will take.


Further Reading

HTML Practice Exercise

Example of Column Properties in CSS

CSS Box Model

Examples of Outline Properties in CSS

Styling Links and Lists

You may also like...