Display and positioning
Before Flexbox and Grid, you need to understand normal flow: how the browser places elements by default. Then you'll learn to take elements out of the flow with position.
Block vs inline
display |
Starts a new line? | Width/height work? | Examples |
|---|---|---|---|
block |
Yes | Yes | div, p, h1, section |
inline |
No | No (only horizontal padding/margin push things) | span, a, strong |
inline-block |
No | Yes | Buttons, badges |
none |
Removed completely | — | Hidden elements |
flex / grid |
Block container whose children follow flex/grid rules | Yes | Layouts (next lessons) |
Hiding things
display: none: removed from the layout and from screen readers.visibility: hidden: invisible, but still takes up space.opacity: 0: invisible but still clickable (careful!).
Positioning
The position property, combined with top, right, bottom, left and z-index, moves elements.
relative: nudge from its normal place
absolute: placed relative to the nearest positioned ancestor
This is the classic pattern for badges, icons and overlays:
The golden pattern: parent
position: relative;+ childposition: absolute;. The child is placed relative to the parent. Without a positioned parent, it's placed relative to the whole page.
fixed: stuck to the viewport
sticky: normal until you scroll past it
The site header on this website uses position: sticky.
Stacking with z-index
When positioned elements overlap, z-index decides which is on top: higher numbers sit closer to you. It only works on positioned (or flex/grid) elements.
Practice
Build a product image card with: an image, a "−20%" sale badge in the top-left corner (absolutely positioned), and a heart "favourite" button in the top-right. Then add a sticky "Add to cart" bar at the bottom of a scrollable product description.
1.A child has position: absolute; top: 0; right: 0. What is it positioned relative to?
2.Which hides an element but keeps its space in the layout?