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, let's arrange the placement so elements don't go wild and step on each other."
๐ 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:
CSS
.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.
CSS
.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:
CSS
.container {
display: flex;
justify-content: center; /* Horizontal alignment */
align-items: center; /* Vertical alignment */
flex-direction: row; /* Can be 'row' or 'column' */
}
๐ง Important item properties:
CSS
.item {
flex-grow: 1;
}
๐งช Simple Flexbox Example:
CSS
.flexbox {
display: flex;
gap: 20px;
justify-content: space-between;
}
HTML
<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:
CSS
.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:
HTML
<div class="grid-container">
<div class="grid-item">A</div>
<div class="grid-item">B</div>
<div class="grid-item">C</div>
</div>
CSS
.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: Start Here
Use @media query
to create responsive layouts based on screen size.
๐งช Basic Media Query Example:
CSS
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}
Meaning: when screen โค 768px (tablet/mobile), change flex to vertical.