Lesson 4: Layout with CSS

The Box Model

Every HTML element is a rectangular box consisting of:

  • Content: The actual content (e.g., text or image).
  • Padding: Space between content and the border.
  • Border: The outer edge of the element.
  • Margin: Space outside the border.

Example:

div {
  width: 300px;
  height: 200px;
  padding: 20px;
  border: 2px solid black;
  margin: 10px;
}

Positioning Elements

  • Static Positioning (default): Elements appear in the order they are written.
  • Relative Positioning: Adjusts position relative to its normal position.
    div { position: relative; top: 10px; left: 20px; }
  • Absolute Positioning: Places elements relative to their nearest positioned ancestor.
  • Fixed Positioning: Sticks elements to the viewport.

Flexbox for Layouts

Flexbox makes it easy to align and distribute elements.

Example: Horizontal Navigation Bar

<div class="navbar">
  <a href="#home">Home</a>
  <a href="#about">About</a>
  <a href="#contact">Contact</a>
</div>
.navbar {
  display: flex;
  background-color: #333;
}
.navbar a {
  color: white;
  padding: 10px;
  text-decoration: none;
}
.navbar a:hover {
  background-color: #555;
}

CSS Grid for Complex Layouts

Grid is ideal for creating structured layouts.

Example:

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
  gap: 10px;
}
.grid div {
  background: lightblue;
  padding: 20px;
  text-align: center;
}