๐ฆ CSS Box Model Essentials
Every HTML element is treated as a box, and the Box Model defines how that box behaves:
Part | Description |
---|---|
margin |
Space outside the element. Pushes it away from other elements. |
padding |
Space inside the element, between content and border. |
width |
Sets the horizontal size of the content area. |
height |
Sets the vertical size of the content area. |
box-sizing |
Controls how width and height are calculated (with or without padding). |
๐ ๏ธ Example in VS Code:
.box {
width: 300px;
height: 200px;
padding: 20px;
margin: 30px;
box-sizing: border-box;
}
๐ง 23 More Related Topics You Should Learn
๐งฑ Layout & Spacing
max-width / min-width
โ Limit how wide an element can grow or shrinkmax-height / min-height
โ Same for heightoverflow
โ Controls content that exceeds the box (hidden, scroll, auto)display
โ Defines how an element behaves (block, inline, flex, etc.)visibility
โ Show or hide elements (visible, hidden)z-index
โ Layering elements (higher value = on top)position
โ Controls placement (static, relative, absolute, fixed)top, right, bottom, left
โ Used with position to move elements
๐จ Styling the Box
border
โ Adds a border around the boxborder-radius
โ Rounds the cornersbox-shadow
โ Adds shadow effectsbackground-color
โ Sets background colorbackground-image
โ Adds an image backgroundopacity
โ Controls transparency
๐งฉ Advanced Box Behavior
flex
โ Used in Flexbox layoutgrid
โ Used in Grid layoutalign-items / justify-content
โ Align content inside flex/grid containersgap
โ Space between items in flex/gridaspect-ratio
โ Controls width-to-height ratioobject-fit
โ Controls how images fit inside boxes
๐ Measurement Units
px, em, rem, %, vh, vw
โ Different ways to size boxescalc()
โ Perform math inside CSS (width: calc(100% - 50px))
๐งช Debugging & Tools
- Developer Tools โ Use browser dev tools to inspect box model live
๐ป How to Use in VS Code
Create an HTML file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box">Hello Box!</div>
</body>
</html>
Create a CSS file (style.css
):
.box {
width: 300px;
height: 150px;
padding: 20px;
margin: 40px;
border: 2px solid black;
box-sizing: border-box;
background-color: lightblue;
}
Open in Live Server (VS Code extension) to see changes instantly.