CSS3 Box Model

CSS3 Box Model

All the HTML elements in the webpage are considered boxes. From the development standpoint, the CSS3 box model refers to the design and layout of the webpage.

The CSS3 box model is primarily a box that includes almost every HTML element. It comprises margin, padding, borders, and the actual content.

The image displayed below defines the box model.

CSS3 Box Model

Explanation of different parts of this box model.

  • The content of a box is a place where image and content appears.
  • Margin is an area outside the border of an image or element
  • Padding is the spacing between content and border. Generally, padding is transparent
  • The border is an area that surrounds content and padding.

The above-mentioned box model allows us to apply border around elements and define spacing between elements.

Example of CSS3 Box Model

<!DOCTYPE html>
<html>
<head>
    <title>
        CSS3 Box Model
    </title>
    <style>
        div {
            background-color: cornflowerblue;
            width: 400px;
            border: 15px solid gold;
            padding: 50px;
            margin: 35px;
        }
    </style>
</head>
<body>
    <h2>Example of Box Model</h2>
    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis dolores vero excepturi laudantium. Ad vitae
        cupiditate minima quod deleniti. Repudiandae dicta reprehenderit molestiae odio illum voluptatibus ea pariatur
        nisi beatae?
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, nam. Sequi animi aperiam nulla doloribus non
        vitae ullam distinctio, nostrum earum! Impedit praesentium neque eligendi repudiandae minus fugit, possimus
        consequuntur!
    </div>
</body>
</html>

 

The output of this code will be

CSS3 Box Model

Width and Height of an Element

To specify the width and height of an element in all the browsers, you need to have a working knowledge of the CSS box model.

Example of CSS3 Model

<!DOCTYPE html>
<html>
<head>
    <title>
        CSS3 Box Model
    </title>
    <style>
        div {
            width: 420px;
            padding: 10px;
            border: 5px solid red;
            margin: 0;
        }
    </style>
</head>
<body>
    <h2>Total width of an element will be:</h2>
    <img src="CSS.png" alt="CSS3" width="450" height="220">
    <div>
        The total width of an element is 450px and total height is 250px.
    </div>
</body>
</html>

 

The output of this code will be

CSS3 Box Model

The total width of an element will be calculated in this way

Total width = width + left padding + right padding + left margin + right margin + left border + right border.

The total height of an element will be calculated in this way.

Total height = height + top padding + bottom padding + top margin + bottom margin + top border + bottom border

Continue learning more.

External Sources

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model

48