CSS Box Model

  • The CSS box model defines the design and layout of the webpage. Each HTML element is enclosed in boxes that have four main parts: content, padding, border, and margin. The box model is used to set the spacing and sizing of elements on a website.

    Content: This box includes the text and images.
    Padding: It creates a clear space around the content to separate elements on the page, allowing for a more organized layout.
    Border: It wraps both the padding and the content.
    Margin: It is also transparent and extends beyond the border to create a clear area around it.

    In short, the box model helps developers control spacing and borders around HTML elements.

    .box {
        padding: 20px;
        border: 5px solid #3498db;
        margin: 30px;
        background-color: #ecf0f1;
        font-family: sans-serif;
    }

    Width and Height of an Element

    Understanding how the CSS box model works is crucial for setting the height and width of an element across all browsers.

    Remember, when the width and height of an element are set with CSS, it only sets the height and width properties of the content area. Therefore, padding and borders should also be included while calculating an element’s total width and height.

    .container {
        width: 200px;
        height: 100px;
        padding: 20px;
        border: 5px solid #2ecc71;
    }

    Calculating the Total Width of an Element

    To find the total width of an element, add the following together:
    Total Width = content width + padding (left + right) + border (left+ right border)

    Determining The Total Height of an Element

    To determine the full height of an element, use this formula:
    Total Height = content height + padding (top + bottom padding) + border (top + bottom border)

    .box {
        width: 300px;
        height: 150px;
        padding: 20px;
        border: 10px solid #e67e22;
        background-color: #fdf2e9;
    }

    Calculation

    Applied Values

    • Content: 300px × 150px

    • Padding: 20px × 2 = 40px

    • Border: 10px × 2 = 20px

     So:

    • Total Width = 300 + 40 + 20 = 360px

    • Total Height = 150 + 40 + 20 = 210px

    Note: The margin property adds space outside the element but is not counted when measuring the element’s actual width or height.

  • HTML
    CSS
    JS
  • Ad #1
    Ad #2
    Scroll to Top