Quick Cheatsheet for Centering Elements
3 Ways to Center Images and Text
Centering content with CSS is very easy. It is probably among the first lessons all of us learn about CSS. However, it is very simple to forget. Today, we’re quickly going to go over three simple ways to center elements.
Method 1: Centering with Flexbox
HTML (paragraph element)
<div id="container">
<div id="content">
<p> Text-Element </p>
</div>
</div>
HTML (image element)
<div id="container">
<div id="content">
<img src="https://image.shutterstock.com/image-illustration/online-statistics-data-analytics-digital-260nw-1911783457.jpg">
</div>
</div>
CSS
#container {
height: 500px;
width: 100%; display: flex;
justify-content: center;
align-items: center;
}
Note that the content that is being centered is located inside a child div. To center this child div, we are styling the parent div. The main area of focus is the latter half of the code above.
- Change the code to
display: flex
- Justify content will center the content horizontally. This happens because the flex-direction is row (by default). If you change flex-direction to column, it will center the content vertically.
- Align items will center the content vertically. Again, this only happens because the flex-direction is row. If you change flex-direction to column, the align-items will center the content horizontally.
Method 2: Centering with Grid
HTML
<div id="container2">
<div id="content">
<img id="i1" src="https://image.shutterstock.com/image-illustration/online-statistics-data-analytics-digital-260nw-1911783457.jpg">
<img id="i1" src="https://image.shutterstock.com/image-illustration/online-statistics-data-analytics-digital-260nw-1911783457.jpg">
</div>
</div>
CSS
#container2{
display:grid;
place-items: center;
}
Again, we follow this format of a div nested within another div. Unlike the previous method, we are using display: grid
. With grid, we will use place-items
to center the grid items. This centers the grid items vertically and horizontally.
Also, as shown in the screen above, it works for text and images.
Method 3: Centering with Text Align
HTML (for text)
<p> Rochester </p>
HTML (for images)
<div id="i33">
<img src="https://image.shutterstock.com/image-illustration/online-statistics-data-analytics-digital-260nw-1911783457.jpg">
</div>
CSS
p {
text-align:center;
}
#i33{
text-align:center;
}
For text elements, like heading elements and paragraph elements, you can simply use text-align:center
with no problem. With images, it is not that simple. With images, you must place them in divs and center that div with text-align.