Reputation: 137
I have a html with the following format
<body>
<section></section>
<section></section>
<section></section>
</body>
The body is the entire page, I want each section to be horizontally centered in the body.
Upvotes: 1
Views: 107
Reputation: 53709
They are centered by default (with 100% width). If you specify a width < 100%, use a left/right margin of auto
to center them horizontally.
body {
border: 1px solid black;
padding: 1em;
}
section {
width: 80%;
margin: auto;
border: 1px solid red;
height: 1em;
}
<body>
<section></section>
<section></section>
<section></section>
</body>
You can also use display: flex; align-items: center; flex-direction: column;
on the parent to center the sections horizontally.
body {
border: 1px solid black;
padding: 1em;
display: flex;
align-items: center;
flex-direction: column;
}
section {
width: 80%;
border: 1px solid red;
height: 1em;
}
<body>
<section></section>
<section></section>
<section></section>
</body>
Upvotes: 1