"I am Saqib Jahangir. A passionate vlogger, software engineer, and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Box Model in CSS

 

๐Ÿงฑ Box Model in CSS

The CSS Box Model is the fundamental structure that wraps every HTML element. It defines how elements are displayed and how spacing is calculated.

Each element is essentially a box consisting of the following areas (from innermost to outermost):

๐Ÿ“ฆ 1. Content

The actual content like text, images, or other HTML inside the element.

width: 200px;
height: 100px;

๐Ÿ“ 2. Padding

The space inside the element, around the content. It pushes the content away from the edges of the element.

padding: 10px; /* space between content and border */

๐Ÿ–ผ️ 3. Border

The line surrounding the padding (and content).

border: 2px solid black;

๐Ÿ“ 4. Margin

The space outside the border, creating space between elements.

margin: 20px; /* space between elements */

Visual Representation of the Box Model:

|<----------- Margin ----------->|
|  |<-------- Border -------->|  |
|  |  |<----- Padding ----->|  |  |
|  |  |  |   Content       |  |  |  
|  |  |<------------------->|  |  |
|  |<------------------------->|  |
|<------------------------------->|

๐Ÿงฎ Box Model Dimensions Formula

To calculate the total space an element takes up:

Total Width = margin + border + padding + content width  
Total Height = margin + border + padding + content height

Use the box-sizing property to control how this calculation works:

box-sizing: content-box; /* Default: padding & border added outside width */
box-sizing: border-box;  /* Includes padding & border within width */

๐Ÿงช Example:

<div style="width: 300px; padding: 20px; border: 5px solid blue; margin: 30px; box-sizing: border-box;">
  This is a box
</div>

 

Popular Posts

Setting Up Your First Project Folder and Installing XAMPP or WAMP

Frontend vs Backend vs Full Stack