Display & Position
The Display Property
display controls how an element behaves in the page layout:
.a { display: block; } /* takes the full width, starts on a new line (div, p, h1) */
.b { display: inline; } /* flows with text, ignores width/height (span, a) */
.c { display: inline-block; } /* flows like inline, but accepts width/height/margin */
.d { display: none; } /* removed from the page entirely — takes up no space */
.e { display: flex; } /* turns this element into a flex container (next chapter) */
.f { display: grid; } /* turns this element into a grid container */
Note the difference between display: none and visibility: hidden — the
former removes the element from layout completely, while the latter hides it but still reserves
its space.
The Position Property
.static { position: static; } /* default — normal document flow, top/left/etc. ignored */
.relative { position: relative; top: 10px; left: 10px; } /* offset from its normal position */
.absolute { position: absolute; top: 0; right: 0; } /* positioned relative to nearest positioned ancestor */
.fixed { position: fixed; bottom: 0; width: 100%; } /* positioned relative to the browser window, stays put on scroll */
.sticky { position: sticky; top: 0; } /* relative until it hits the given offset, then sticks like fixed */
Key rule for absolute positioning: an absolutely-positioned element is placed
relative to its nearest ancestor that has position set to anything other than
static. This is why you'll often see a parent with position: relative
used purely as a positioning anchor for an absolutely-positioned child:
.card {
position: relative;
}
.card .badge {
position: absolute;
top: 10px;
right: 10px;
}
Overflow
Controls what happens when content is too big for its box:
.box {
overflow: visible; /* default — content spills out */
overflow: hidden; /* extra content is clipped and hidden */
overflow: scroll; /* always show scrollbars */
overflow: auto; /* scrollbars only when needed */
overflow-x: auto;
overflow-y: hidden;
}
Float & Clear
Float predates Flexbox and Grid, but it's still useful for wrapping text around an image and for understanding older layouts:
img.float-left {
float: left;
margin-right: 15px;
}
/* Stops an element from wrapping around a floated element */
.clearfix {
clear: both;
}
Z-index
z-index controls the stacking order of overlapping positioned elements — higher values
sit on top of lower ones. It only works on elements with a position other than
static.
.modal-overlay {
position: fixed;
inset: 0;
z-index: 100;
}
.modal-box {
position: relative;
z-index: 101;
}