Centering elements with CSS y HTML: a quick tutorial

1 min

January 07, 2023

Table of contents
  1. Conventions
  2. Using margin-auto
  3. To center vertically
  4. Using display-flex
  5. Using display-grid
CSS image

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.”

Parent
Child

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:
Child content

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:
Child content

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:
Child content

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:
Child content

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!


Camilo Rincon
Camilo Rincon

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

youtube logotiktok logo
© 2023, CARLMULTIMEDIA, from Colombia 💛💙❤️ to the World 🌎