Learn two different ways to center align your webpage layout with CSS.
Let’s say you’re styling an article layout for your website, and you want to center align the <article>
element horizontally exactly in the middle of your page.
You can do that in a couple of ways. The most simple, and classic approach to center align elements horizontally is by using the CSS property margin
and set it’s left and right values to auto
.
You can follow along using the free CodePen editor.
Take the following basic HTML markup for an article layout:
<article>
<h1>Title for your article</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad aut
dignissimos, doloribus accusantium provident nemo a voluptatibus nihil
recusandae perferendis nesciunt quae illo cum eos dolore esse, architecto
reprehenderit error.
</p>
</article>
And the following CSS declaration block:
article {
max-width: 640px;
margin-left: auto;
margin-right: auto;
}
This will center align your article layout exactly in the middle of your webpage.
The max-width
property is required to center align elements horizontally because otherwise, the text will automatically span from the left to the right edge of your page.
Center align horizontally with flexbox
You can also center align by using the modern flexbox
property. Due to the way flexbox
passes down properties to child elements, the simplest way to center align your layout is to wrap your <article>
element in another element, and then add the flexbox
properties to that new parent element.
Let’s wrap the article element from earlier with <main>
element:
<main>
<article>
<h1>Title for your article</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad aut
dignissimos, doloribus accusantium provident nemo a voluptatibus nihil
recusandae perferendis nesciunt quae illo cum eos dolore esse, architecto
reprehenderit error.
</p>
</article>
</main>
And move the flexbox properties (not the max-width
) from the article { }
declaration block to a new main { }
block:
main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
article {
max-width: 640px;
}
That will work identically to the margin: auto
declaration you saw previously.