When it comes to centering elements in CSS, there are a few different methods to choose from. One of the most popular methods is using display:flex and justify-content:center, as we discussed in our previous blog post. However, there is another method that is just as fast and even more flexible: using display:grid and place-items:center.

Here’s how it works:

  1. First, create a container for your element. This can be a <div> or any other element that you want to center.
  2. Add the following CSS properties to your container:
display: grid;
place-items: center;

The display:grid property sets the container to be a grid container, which allows us to manipulate the placement of its child elements. The place-items:center property centers the child elements both horizontally and vertically.

  1. Finally, add your element to the container. You can add any type of element you want, whether it’s text, an image, or even another container.

And that’s it! With just a few lines of CSS, you can center any element both vertically and horizontally on your web page. Here’s an example of what the final code might look like:

<div class="center">
  <h1>Hello, world!</h1>
</div>

<style>
  .center {
    display: grid;
    place-items: center;
  }
</style>

This method is not only fast and easy to implement, but it’s also highly customizable. With grid, you can create more complex layouts and manipulate the placement of elements with more precision than with flexbox. For example, you can use grid-template-columns and grid-template-rows to define the size and layout of grid cells, and grid-column and grid-row to position elements within those cells.

In conclusion, while display:flex and justify-content:center are great options for simple centering tasks, display:grid and place-items:center offer even more flexibility and control over element placement. So the next time you need to center an element on your web page, consider using grid instead of flexbox.