Centering elements with CSS y HTML: a quick tutorial
1 min
January 07, 2023
Table of contents

Would you like to center elements on your website quickly and easily? In this article we will teach you how to do it using CSS and HTML.
“There are different ways to center elements in CSS: using the property margin: auto, using the property display: flex along with justify-content: center, and using the property display: grid along with place-items: center.”
Conventions
“You will find in the mentioned examples that the parent will be green and the child red.”
Using margin-auto
The “margin: auto” property works as long as the element has a specific width and is within a parent element with a determined width. For example:
.parent {
width: 500px;
}
.child {
width: 200px;
margin: auto;
}
<div class="parent">
<div class="child">Child content</div>
</div>
For example:This would center the “child” element horizontally within the “parent” element.
To center vertically
To center the element vertically, you can use the display: flex and align-items: center
.parent {
display: flex;
align-items: center;
height: 500px;
}
.child {
width: 200px;
}
<div class="parent">
<div class="child">Child content</div>
</div>
For example:Using display-flex
“Another way to center elements in CSS is using the property display: flex along with justify-content: center. This works similarly to margin: auto, but it is more versatile since it can be used to center elements both horizontally and vertically.”
.parent {
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 200px;
height: 100px;
}
<div class="parent">
<div class="child">Child content</div>
</div>
For example:With this, the “child” element would be perfectly centered both horizontally and vertically within the “parent” element.
Using display-grid
“Another way to center elements in CSS is using the property display: grid along with place-items: center. This works similarly to justify-content: center and align-items: center, but in fewer lines since it can be used to center elements both horizontally and vertically, just make sure it is compatible with all browsers, you can check this on the site can I use.”
.parent {
display: grid;
place-items: center;
}
.child {
width: 200px;
height: 100px;
}
<div class="parent">
<div class="child">Child content</div>
</div>
For example:We hope this article has helped you understand how to center elements in CSS and HTML easily and quickly. Good luck with your web projects!

Multimedia Engineer, Software Engineer front-end, entrepreneur, creating and sharing experiences and resources for developers.