Block vs inline directions in CSS
Published on in CSS and CSS for JS Devs course
Block elements stack on top of each other. Inline elements are placed side by side.
Table of contents
Web pages vs paper documents
Web pages are like paper documents.
- Individual words are inline and placed side by side, from left to right (or right to left in some languages).
- Some words are combined into blocks (e.g. headings and paragraphs) that stack on top of each other, from top to bottom (or bottom to top in some obscure languages).
So, that's the two directions of CSS: block and inline.
And that's how display: block
and display: inline
work too:
- Block elements (
display: block
) take the full available width by default so that they stack on top of each other. Think of e.g. headings, paragraphs and<div>
elements. - Inline elements (
display: inline
) are placed side by side. Think of e.g. individual words and<span>
elements.
This is very basic, but explaining block and inline directions by comparing a web page to a regular paper document was somehow eye-opening to me. I like this mental model that I learned from Josh W Comeau's CSS for JavaScript developers course (Module 1).
Logical properties
Understanding the two directions is also essential for understanding logical properties in CSS.
For example,
when working with right-to-left (RTL) languages,
you might want to use
margin-inline-start
and margin-inline-end
instead of
margin-left
and margin-right
.
The latter properties would be in reverse or "wrong" order
when working with RTL languages.