CSS Layout Examples
This page demonstrates real-world layout patterns using modern CSS techniques. Each example includes complete HTML and CSS code that you can use in your projects.Centering Content
Centering a div has become somewhat of a joke in web development, but modern CSS makes it straightforward. Here are four proven methods.Flexbox Centering (Recommended)
Using flexbox to vertically and horizontally center content is usually the preferred method. It requires just three lines of code.Grid Centering
The grid module works similarly to flexbox and is a common choice when you’re already using grid in your layout.Transform Centering
Transform centering uses CSS transforms and absolute positioning to center an element.Table Centering
Table centering is an older technique useful when working with legacy browsers.vertical-align: middle for centering. Requires fixed width and height on parent.
Box-Sizing Reset
Reset the box-model so thatwidth and height are not affected by border or padding.
- The first box uses
border-box, so padding and border are included in the 120px width/height - The second box uses
content-box(browser default), so padding and border are added to the 120px, making it larger - This demonstrates why
border-boxis generally preferred for predictable layouts
Evenly Distributed Children
Distribute child elements evenly within a parent element using Flexbox.space-between: First item at start edge, last item at end edge, equal space between itemsspace-around: Equal space around each item, with half-space at the edges
flex-direction: row) and vertical (flex-direction: column) containers.
Footer at the Bottom
Ensure the footer stays at the bottom of the page, even when content is short.Using Flexbox
- Body becomes a flex container spanning the full viewport height
margin-top: autoon footer pushes it to the bottom- Main content doesn’t stretch, but footer is always at the bottom
Using Grid
- Creates a grid with two rows
- First row (main) gets
1fr- fills available space - Second row (footer) gets
auto- only takes space it needs - Footer is always at the bottom, main stretches to fill
Flexbox Cheat Sheet
Container Properties
Item Properties
Tips and Best Practices
- Use Flexbox for one-dimensional layouts - When arranging items in a single row or column
- Use Grid for two-dimensional layouts - When you need control over both rows and columns
- Always include box-sizing reset - Makes sizing more predictable
- Use modern viewport units with fallbacks -
dvhanddvwwithvhandvwfallbacks - Test responsive behavior - Verify layouts work at various viewport sizes
- Consider accessibility - Avoid using
orderproperty, as it can confuse screen readers