Demo starter files
Some things in CSS are a bit more complicated than it seems like they should be. Centering content vertically is one of them. The root of this "problem" is that the height of a web document is much more variable than the width, which basically just depends on the width of user's screen. The height can be almost infinite.
The CSS block model is what's called "vertically-biased". You set the width, and the height is inherently variable.
The inline layout model is "horizontally-biased". You set the height (either by setting a font size or line height), and the width depends on your text.
This demo tackles 3 different ways of centering content vertically within a container.
Line Height - This method is probably the most common because it doesn't require breaking the flow of the document. Basically we combine the block and inline layout models, putting something horizontally biased inside something vertically biased. We set a container
width. Then, rather than set a
heighton the container, we expand the
line-heightinside that container. If there's only one line of text,
In CSS, inline text can be shifted to the top, middle, or bottom within its line-height. That's the already familiar
So where's the trick? Inline-block elements sit on a line of text, and can contain any kind of additional content.
CSS Tables - Very similar to line height. Content within a table cell can be vertically aligned just like a tall line height.
Fixed/Absolute Positioning - Requires breaking the document flow and has rare use cases, but in those cases it's pretty handy!
- Bonus: Flexbox method - Flexbox makes vertically centering content very easy, but all of the flexbox related properties are well beyond the scope of this little demo. A flexbox method is included here (for reference, for science!) but we will not talk about it in detail.