CSS Layout: Positioning and Modern Techniques
Master modern CSS layout techniques including positioning, Flexbox, Grid systems, and responsive design to create professional web layouts.
Now that the design looks good, it's time to arrange the layout. In this lesson you'll learn how to position elements properly, build layouts using Flexbox and Grid, and create responsive experiences for different screen sizes.
Positioning: Keeping Elements in Place
CSS has the position property to control how elements "stick" to the page.
Types of Position
| Type | Brief Description |
|---|---|
static | Default (follows HTML flow) |
relative | Offset relative to initial position |
absolute | Sticks to nearest positioned parent |
fixed | Sticks to viewport (doesn't scroll) |
sticky | Hybrid of relative + fixed (sticks when scrolling) |
Example
.box {
position: relative;
top: 20px;
left: 30px;
}z-index: Who's On Top?
z-index controls the stacking order of elements (z-axis). Higher value = more forward.
.card {
position: absolute;
z-index: 10;
}Useful so popups/modals don't get covered by other content. Think of it like Photoshop layers.
Flexbox: Stress-Free Layouts & Centering
Important Container Properties
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
}Important Item Properties
.item {
flex-grow: 1;
}Simple Flexbox Example
.flexbox {
display: flex;
gap: 20px;
justify-content: space-between;
}<div class="flexbox">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>| Property | Function |
|---|---|
justify-content | Horizontal position (start, center, end, space-between) |
align-items | Vertical position (start, center, stretch, end) |
flex-direction | Layout order: row / column |
CSS Grid: For More Complex Layouts
Grid is like Flexbox's "matrix" version — perfect for 2D layouts (rows & columns).
Basic Example
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}Important Properties
| Property | Function |
|---|---|
grid-template-columns | Number & width of columns |
grid-template-rows | Number & height of rows |
gap | Space between elements |
grid-column / row | For merging columns/rows (span) |
CSS Grid Example
<div class="grid-container">
<div class="grid-item">A</div>
<div class="grid-item">B</div>
<div class="grid-item">C</div>
</div>.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}1fr = 1 fraction of available space. Think of it as: 1 slot out of 3 equally divided slots.
Responsive Layout
Use @media query to create responsive layouts based on screen size.
Basic Media Query Example
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}Meaning: when screen ≤ 768px (tablet/mobile), change flex to vertical.
