Loading

Box Model

  • CSS Box model is a fundamental concept in web Design and layout.
  • This describes how elements on a webpage are structured and how their dimensions are calculated.
  • It consists of several layers or "boxes" that wrap around an HTML element, determining its layout and spacing.

Box model:

The CSS Box Model consists of four essential components:

Content: 

  • This is the innermost layer.
  •  It represents the actual content of the HTML element, such as text, images. 
  • The content dimensions are set by the width and height properties in CSS.

Padding:

  •  The padding is the space between the content area and the element's border.
  •  It can be set individually for each side (top, right, bottom, left). 
  • Padding adds spacing within the element.

Border: 

  • The border provides a visible boundary for the element. and it surrounds the padding and content area.
  • It is controlled by the border property, which includes properties like border-width, border-style, and border-color. 

Margin: 

  • The margin is the space between the element's border and neighbouring elements.
  •  It controls the spacing between elements on a webpage. 
  • The margin property is used to set margins for each side (top, right, bottom, left) individually.

Key Points:

  • Box Model applies to all block-level and replaced elements in CSS. 
  • using the CSS Box Model effectively, you can control the spacing, layout, and visual appearance of elements on your web page, ensuring a consistent and visually appealing design.

Box-Sizing Property

 

The box-sizing property controls how the width and height of an element are calculated:

  • content-box (default): The width and height include only the content. Padding, border, and margin are added outside this area.
  • border-box: The width and height include content, padding, and border, but not the margin.
.box {
    box-sizing: border-box;
}

Margin Collapsing

 

When vertical margins of adjacent block elements meet, they collapse into a single margin. The resulting margin is equal to the largest margin value.

<div class="box" style="margin-bottom: 20px;">Box 1</div>
<div class="box" style="margin-top: 30px;">Box 2</div>

The space between Box 1 and Box 2 will be 30px (the larger of the two margins), not 50px.


Responsive Design with Box Model

 

To create responsive layouts, use relative units like percentages for width, margin, and padding. Use media queries to adjust the layout based on screen size.

.box {
    width: 50%;
    padding: 10%;
    border: 2px solid black;
    margin: 5%;
}

@media (max-width: 600px) {
    .box {
        width: 90%;
        padding: 5%;
        margin: 2%;
    }
}