In CSS, the position property determines how an element is placed in the layout and how it interacts with other elements around it. It defines whether the element follows the normal document flow, can be offset using coordinates (top, right, bottom, left), or stays fixed in place.
The type of positioning you choose affects:
Common positioning values include static, relative, absolute, fixed, and sticky, each serving different layout purposes.
Static is the default positioning for all elements. Elements positioned statically are placed in the normal document flow — meaning they appear one after another in the order they are written in the HTML, without any offset changes. Properties like top, right, bottom, and left have no effect on static elements.
div {
position: static;
}Relative positions the element relative to its original position in the normal flow. Using top, left, right, or bottom will visually move the element without affecting other elements’ positions. The space originally occupied by the element remains reserved.
div {
position: relative;
top: 10px; /* moves down */
left: 20px; /* moves right */
}Absolute removes the element from the normal document flow and positions it relative to the nearest ancestor that is not static. If no such ancestor exists, it is positioned relative to the <html> element (the page itself). Other elements will ignore its space.
div {
position: absolute;
top: 50px;
left: 30px;
}Fixed positions the element relative to the browser’s viewport, meaning it stays in place even if the user scrolls the page. This is useful for sticky headers, floating buttons, or navigation bars.
div {
position: fixed;
top: 0;
right: 0;
}Sticky acts like relative until a specified scroll threshold is reached, after which it behaves like fixed. It’s useful for headers or table columns that should remain visible while scrolling within their container.
div {
position: sticky;
top: 0; /* sticks when reaching top of viewport */
}Create five boxes with different position values. Add text labels inside each box and use borders or background colors to distinguish them. Try scrolling to see how fixed and sticky behave.
<div style={{
position: "relative",
top: "20px",
left: "20px",
backgroundColor: "#add8e6",
padding: "10px"
}}>
Relative Box
</div>
<div style={{
position: "absolute",
top: "100px",
left: "100px",
backgroundColor: "#f08080",
padding: "10px"
}}>
Absolute Box
</div>
<div style={{
position: "fixed",
top: "10px",
right: "10px",
backgroundColor: "#90ee90",
padding: "10px"
}}>
Fixed Box
</div>
<div style={{
position: "sticky",
top: "0px",
backgroundColor: "#ffa500",
padding: "10px"
}}>
Sticky Box
</div>You can copy and paste this code in your IDE to run!
Ask the AI if you need help understanding or want to dive deeper in any topic