CSS Layout defines how elements are arranged on a page. Common layout modes include block, inline, flexbox, grid, float, and positioning. Understanding these helps you build clean, responsive, and accessible layouts.
Block elements occupy the full available width and push following content to a new line. Inline elements sit beside each other in the same line.
/* Compare block and inline elements */
div {
display: block;
}
span {
display: inline;
}
A <div> stretches across its container, while <span> boxes sit inline like words in a sentence.
Flexbox is ideal for centering items, creating navbars, and distributing space along a single axis.
/* Horizontal flex layout with gaps */
.flex-container {
display: flex;
gap: 10px;
justify-content: center;
align-items: center;
}
Children of .flex-container are placed in a row, centered both horizontally and vertically with equal gaps.
Grid lets you define rows and columns, making it perfect for dashboards, galleries, and full-page layouts.
/* Three equal-width grid columns */
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
The container is split into three equal columns. Each direct child automatically occupies one column cell.
Positioning moves elements relative to their normal place or their container, useful for badges, overlays, or fine-tuning.
/* Slightly offset a box from its normal spot */
.box-relative {
position: relative;
top: 10px;
left: 20px;
}
The element keeps its layout space but is visually shifted down and right, without affecting surrounding elements.
Floats allow text to wrap around elements, such as images, but are less common for complex layouts today.
/* Float a box left so text wraps around it */
.box-float {
float: left;
width: 30%;
margin-right: 10px;
}
The floated box hugs the left side, and text flows around it on the right. Remember to clear floats so parent elements wrap correctly.
@media queries to adjust for mobile, tablet, and desktop.%, fr, and auto over fixed pixel widths..flex-container with 4 boxes and center them horizontally with justify-content: center;.grid-template-columns: repeat(2, 1fr); and set a gap between items.position: absolute; on a child inside a relatively positioned parent.