← Back to Tutorials Chapter 4

Layout & Positioning

The display Property

The display property controls how an element behaves in the layout.

block

p { display: block; }

inline

span { display: inline; }

inline-block

button { display: inline-block; }

none

.hidden { display: none; }
Note: visibility: hidden hides the element but keeps its space. display: none removes the element entirely from the layout.

max-width

div {
  max-width: 800px;
  margin: 0 auto;
}

Positioning

static (default)

Elements appear in normal document flow. The top, right, bottom, and left properties have no effect.

relative

Offset from its normal position without affecting surrounding elements.

div {
  position: relative;
  top: 10px;
  left: 20px;
}

absolute

Positioned relative to the nearest positioned ancestor. Removed from normal flow.

div {
  position: absolute;
  top: 0;
  right: 0;
}

fixed

Positioned relative to the viewport. Stays in place during scrolling.

nav {
  position: fixed;
  top: 0;
  width: 100%;
}

sticky

Toggles between relative and fixed depending on scroll position.

header {
  position: sticky;
  top: 0;
}

z-index

Controls the stacking order of positioned elements. Higher values appear on top.

.overlay {
  position: absolute;
  z-index: 10;
}

Overflow

div {
  overflow: hidden;   /* clip content */
  overflow: scroll;   /* always show scrollbars */
  overflow: auto;     /* show scrollbars only when needed */
}

Float and Clear

img {
  float: left;
  margin-right: 10px;
}

footer {
  clear: both;
}

Alignment

p { text-align: center; }

div {
  width: 50%;
  margin: 0 auto;    /* center block elements */
}
Diagram showing layout and positioning concepts

Practice Task

Create a fixed header that stays at the top of the page, a sidebar with position: sticky, and a main content area that scrolls beneath them.