Master the CSS display and position properties to control how elements are rendered and placed on the page, from block-level layouts to precisely positioned overlays.
Every HTML element has a default display value that determines how it participates in the page layout. Understanding display is fundamental to controlling your layouts.
The most common display values are:
block — The element takes up the full width available and starts on a new line. Examples: <div>, <p>, <h1>.inline — The element only takes up as much width as its content needs and does not start on a new line. Examples: <span>, <a>, <strong>. You cannot set width or height on inline elements.inline-block — A hybrid: the element flows inline like text, but you can set width, height, margin, and padding on all sides.none — The element is completely removed from the layout. It takes up no space and is invisible..card {
display: inline-block;
width: 200px;
height: 150px;
}
.hidden {
display: none;
}Choosing the right display value is the first step in any layout task.
/* static — the default; element follows normal flow */
.default {
position: static;
}
/* relative — offset from its normal position;
the original space is preserved */
.nudged {
position: relative;
top: 10px;
left: 20px;
}
/* absolute — removed from normal flow;
positioned relative to the nearest positioned ancestor */
.overlay {
position: absolute;
top: 0;
right: 0;
}
/* fixed — removed from normal flow;
positioned relative to the viewport (stays on scroll) */
.sticky-header {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
/* sticky — toggles between relative and fixed
depending on scroll position */
.table-header {
position: sticky;
top: 0;
}When you use position: absolute, the element is positioned relative to its nearest positioned ancestor — that is, the closest parent element that has a position value other than static.
If no ancestor is positioned, the element is positioned relative to the initial containing block (usually the <html> element).
A very common pattern is to set position: relative on a parent container (without any offset) and then use position: absolute on a child to place it precisely within that container:
.parent {
position: relative; /* establishes positioning context */
}
.badge {
position: absolute;
top: -8px;
right: -8px;
}The offset properties top, right, bottom, and left only work on elements that have a position value other than static. They control the distance from the corresponding edge of the positioning context.
What happens when you set `position: absolute` on an element whose parent has no explicit position set?