CSS Docs

CSS Box Model

Learn the fundamentals of the CSS Box Model, including padding, border, margin, and element display.

The CSS Box Model is essential for understanding how elements are structured, spaced, and displayed on a webpage.

📦 What is the CSS Box Model?

The CSS Box Model describes how elements are rendered on the page. Every element is a rectangular box consisting of:

  1. Content: The actual text or image.
  2. Padding: Space between the content and the border.
  3. Border: The edge surrounding the padding.
  4. Margin: Space outside the border, separating the element from others.

🧱 Box Model Structure

document.addEventListener("DOMContentLoaded", function() {
const app = document.getElementById("app");
if (app) {
  app.innerHTML = "<h1>Box Model Example</h1>";
}
});

🔄 Box Sizing (box-sizing)

box-sizing defines how the total width and height of an element are calculated.

  • content-box: Default value. Width and height include only the content.
  • border-box: Width and height include content, padding, and border.
document.addEventListener("DOMContentLoaded", function() {
const app = document.getElementById("app");
if (app) {
  app.innerHTML = "<h1>Box Sizing Example</h1>";
}
});

📜 Overflow and Scroll

Controls what happens when content exceeds its container.

  • overflow: Handles both horizontal and vertical overflow.
  • overflow-x: Handles horizontal overflow.
  • overflow-y: Handles vertical overflow.
document.addEventListener("DOMContentLoaded", function() {
const app = document.getElementById("app");
if (app) {
  app.innerHTML = "<h1>Overflow Example</h1>";
}
});

🧩 Display Property

Defines how an element is displayed on the page.

Elements take full width and start on a new line (e.g., <div>).

👁️ Visibility and Positioning

  • visibility: Controls if the element is visible (visible, hidden).
  • position: Specifies how the element is positioned (static, relative, absolute, fixed, sticky).

Determines whether an element is visible or hidden, but hidden elements still occupy space.

document.addEventListener("DOMContentLoaded", function() {
const app = document.getElementById("app");
if (app) {
  app.innerHTML = "<h1>Visibility Example</h1>";
}
});

Controls the placement of elements relative to their normal position or the viewport.

document.addEventListener("DOMContentLoaded", function() {
const app = document.getElementById("app");
if (app) {
  app.innerHTML = "<h1>Position Example</h1>";
}
});

🧪 Try Yourself

document.addEventListener("DOMContentLoaded", function() {
const app = document.getElementById("app");
if (app) {
  app.innerHTML = "<h1>Try Yourself</h1>";
}
});

On this page