Centering elelments used to be pretty hard. Now, there’s lots of way to do it.
Think about how how center things in real life.
- define the dimensions of the container
- measure the center point of the container and the child
- align both center points on both axis
To do this on the web, define (or understand the default) dimensions:
- the width is by default, auto or 100% of the viewport
- define the height, the default is determined by the height of the content
- calculate the center points and align.
The last step is easy with today’s browsers doing the calculation for you.
So the simplest way to center one thing in the browser window:
body {
display: grid;
height: 100vh;
place-items: center;
}
Place-content will use the content box (the parent) to center items together,
while place-items will center the items using the available space (spreading them out) centering each item within the box of its parent.
Other Methods
Display grid the parent, margin: auto the content.
.autobot {
display: flex;
}
.autobot > *{
margin: auto;
}
You can center content in a full-width element by putting display: grid on the parent, with justify-content: center; giving a grid-template-column: one column with the width you want. minmax() works well here:
```css
.full-width-example {
display: grid;
grid-template-columns: minmax(300px, 600px);
justify-content: center;
background-color: rgb(255, 211, 130);
}
```
Leave a Reply