Perfect Padding
How do you make a page where content is nicely centered at a width that looks nice on desktop - but the padding shrinks down to nothing on mobile?
I like clear, text-focused pages, so I use this design pattern all the time - and on this very page! - but it took me a fair while to nail it.
The trick is not to use padding
Basic Process
Your design contains two elements: a container and an object. Such as:
Container | Object |
---|---|
Body | Article |
Column | Blog posts |
Article | Paragraph |
Here's how you do it:
- On the container, set the
padding
to be seen on mobile (I use 2vw) - On the object, put the
max-width
to be seen on desktop (I use 70ch - 90ch) - Center the object in the container.
- On the object, set
margin-left:auto; margin-right:auto
- best for paragraphs because it prevents margin collapse - Or on the container, set
{display: flex; flex-direction: column; align-items:center}
- On the object, set
And you're done! On my sites, I tend to use this to put paragraphs into blog boxes, as well as putting blog boxes in the middle of pages.
Why Does this Work?
- The real purpose of pseudo-padding here is readability. 70ch-90ch is the number of characters the a human reader can comfortably take in at a glance. Content to be read should be emphasised - say by being centered on a page, with the edges of the page de-emphasised, either by being plain (and therefore unremarkable) or muted (allowing the center to pop). It shouldn't touch the edges of a 'visual box' where letters at the edge are muddied by the border-line.
- On desktop, the object floats in the middle of the page.
- It expands only as far as
max-width
allows it to, leaving lots of blank space either side - This gives the impression of 'padding' but we have not used the padding property, because padding cannot shrink and grow
- As we've set a max-width, the content will always expand to that ideal width if it's available: as we shrink the page, the first thing to be swallowed is the pseudo-padding.
- This is correct because the amount of padding is not important: the width of the object is important. The padding is just 'whatever is left over'
- As the page-size shrinks, the object can shrink too - a natural behaviour in HTML. We haven't set
width
ormin-width
- As the object has no padding or margin, it touches the sides of the container and comes into contact with the container's padding you set. This ensures there is always a little padding for mobile users so text isn't muddy on the edges of the phone.