Here’s a CSS position cheat sheet:
Position Property
Relative Positioning:
.relative {
position: relative;
top: 10px; /* or any values */
left: 20px; /* or any values */
}
Absolute Positioning:
.absolute {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
Fixed Positioning:
.fixed {
position: fixed;
top: 0;
right: 0;
}
Sticky Positioning:
.sticky {
position: sticky;
top: 0;
}
Z-Index
Z-Index:
.higher-z {
z-index: 2;
}
.lower-z {
z-index: 1;
}
Centering
Center Horizontally:
.center-horizontally {
margin: 0 auto;
}
Center Vertically:
.center-vertically {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Center Both Horizontally and Vertically:
.center-both {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Floats (Older Approach)
Float:
.float-left {
float: left;
}
.float-right {
float: right;
}
Clear Floats:
.clearfix::after {
content: "";
display: table;
clear: both;
}
Overflow
Overflow:
.overflow-hidden {
overflow: hidden;
}
.overflow-scroll {
overflow: scroll;
}
Overflow X and Y:
.overflow-x-auto {
overflow-x: auto;
}
.overflow-y-hidden {
overflow-y: hidden;
}
Practical Tips
Centering Inside Relative Container:
.parent-relative {
position: relative;
}
.child-centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Fixed Position Within a Container:
.container {
position: relative;
}
.fixed-inside {
position: fixed;
top: 0;
right: 0;
}
Centering Using Flexbox:
.flex-container {
display: flex;
justify-content: center;
align-items: center;
}
This cheat sheet provides a quick reference for common CSS positioning techniques. Adjust the values based on your specific layout requirements. Note that flexbox and grid are modern layout techniques and are preferred for creating complex layouts over older methods like floats.