Centering an entire layout is easy in CSS. Wrap all you HTML in some kind of container, usually a div
:
<body>
<div class="container">
<-- All of the content in here -->
</div>
</body>
We can use CSS flexbox to center the container div easily. All we have to do is:
justify-content
body {
display: flex;
justify-content: center;
}
.container {
width: 80%;
}
Using percentages for your page width allows for flexible pages, however we need to be mindful of line lengths. Blanket percentage widths on very large screens will cause readability issues. It's good practice to also specify a maximum page width to ensure that the line lengths of your text do not get too long.
Use the same HTML:
<body>
<div class="container">
<-- All of the content in here -->
</div>
</body>
.container {
margin: 0 auto;
width: 80%;
max-width: 1024px;
}
There is also an older method for centering which uses automatic margins.
auto
. This will make the left and right margins automatically equal..container {
margin: 0 auto;
width: 80%;
}