To center an element, give it a width that is less than 100% and set its margins to auto
:
section {
width: 700px;
margin: auto;
}
By default, the <section>
takes up the full horizontal space of its parent element. To center it, we need to reduce its width so it is smaller than the parent. In the code snippet above, I used a width of 700px
, but you can also use other units such as em
, rem
, or %
.
Setting the margin
to auto
tells the browser to calculate equal margins on the left and right sides of the element to center it within its parent element.
You can also customize the styles for different screen widths:
/* Width is 600px when viewport is at least 600px wide */
@media (min-width: 600px) {
section {
width: 600px;
margin: auto;
}
}
/* Width is 800px when viewport is at least 800px wide */
@media (min-width: 800px) {
section {
width: 800px;
}
}