banjocode Align Text On The Same Vertical Line Using Flow Layout

Align Text On The Same Vertical Line Using Flow Layout

When there is a lot of text on a page, it's generally looks much better if every paragraph and heading starts at the exact same vertical line. This is a short guide how to do that and still keep the page responsive

2 min read

Creating a centered container

First of all, we want to create a centered container. We’ll create a CSS class that we can apply to all elements that we want to display on the same vertical line.

.centered {
     max-width: 800px; /* the max value of the container */
     margin: 0 auto; /* center the container */
}

Any time this class is added to an element, it will be centered and have a max-width of 800px. As it is only the max-width defined, the container will stil work on mobile devices.

You might want to add some padding as well, so there will be some spacing on smaller devices.

Aligning the text

The text will in this case be aligned if everything is using flow layout. However, a problem might occur if we want to add some padding on a certain text element.

As the padding (especielly left padding) will move the text, it will no longer be aligned. The trick is to use negative margin to “undo” the effect. This will move the text back to the vertical line and add the padding “outside”.

.text-element {
    padding: 16px;
    margin: -16px;
}

I learnt this neat trick from the CSS for Javascript Developers course by Josh W. Comeau, which I highly recommend if you want to learn things like this.