CSS Positioning and Layout
Master the art of controlling element positioning and creating responsive layouts
Learning Outcomes
- Understand and apply different position values: static, relative, fixed, absolute, sticky
- Create responsive website layouts that adapt to different screen sizes
- Implement advanced layouts using Flexbox and CSS Grid
- Control element stacking with z-index
- Apply modern layout techniques for real-world web applications
CSS Positioning
CSS positioning allows you to control exactly where elements are placed on a web page and how they interact with other elements.
Position Property Values
The position
property specifies the type of positioning method used for an element. There are five different position values:
Static (default)
.element {
position: static;
}
Elements render in order as they appear in the document flow.
Relative
.element {
position: relative;
top: 20px;
left: 30px;
}
Positioned relative to its normal position. Other elements aren't affected.
Absolute
.element {
position: absolute;
top: 50px;
right: 20px;
}
Positioned relative to its nearest positioned ancestor (not static).
Fixed
.element {
position: fixed;
bottom: 0;
right: 0;
}
Positioned relative to the viewport. Stays in place during scrolling.
Sticky
.element {
position: sticky;
top: 0;
}
Toggles between relative and fixed based on scroll position.
Z-Index Property
The z-index
property specifies the stack order of elements (which element appears in front).
.element1 {
position: absolute;
z-index: 1;
}
.element2 {
position: absolute;
z-index: 2; /* Appears above element1 */
}
Layout Techniques
Modern CSS provides powerful layout systems to create complex, responsive designs.
Flexbox Layout
Flexbox is a one-dimensional layout method for arranging items in rows or columns.
.container {
display: flex;
justify-content: center; /* Main axis alignment */
align-items: center; /* Cross axis alignment */
flex-wrap: wrap; /* Allow items to wrap */
}
.item {
flex: 1; /* Grow and shrink as needed */
}
CSS Grid Layout
CSS Grid is a two-dimensional layout system that handles both rows and columns.
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: 100px auto;
gap: 10px;
}
.item {
grid-column: 1 / 3; /* Span columns */
grid-row: 1; /* Position in row */
}
Responsive Layout Techniques
Create layouts that adapt to different screen sizes using media queries and flexible units.
/* Mobile-first approach */
.container {
padding: 10px;
}
/* Tablet */
@media (min-width: 768px) {
.container {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
/* Desktop */
@media (min-width: 1024px) {
.container {
grid-template-columns: 1fr 3fr 1fr;
}
}
Interactive Playground
Experiment with different positioning and layout techniques: