How to Center h1 in CSS?

To center align an h1 element, you can use the text-align property. All you need to do is apply text-align: center; on the h1 element and it will automatically center align the h1.

But, it is to be noticed here that text-align: center; aligns only the content(text) of the h1 element to the center, not the h1 element itself.

Here is a working example:

Example:

h1{
   text-align: center;
}

Center Align H1 Using margin: auto

In the last example, we saw that the text-align: center; centers only the content of the h1 element in the center, not the h1 element.

So, if you want to center the whole h1 element, you can take help of the margin:auto; property.

The margin: auto; centers the whole h1 element to the center along with its content. But it is possible only when you have set a fixed width of the h1 element.

Here is a working example:

Example:

h1{
   margin: auto;
   width: 400px;
   background: yellow;
}

Note: Remember that text-align: center; aligns only the content of the element to the center while margin: auto; aligns the whole element itself to the center.


Center Align H1 Using CSS Flexbox

When it comes to aligning HTML elements, be it horizontally or vertically, the CSS flexbox is always the best choice.

CSS flexbox is a flexible layout module that makes the responsive design layout pretty easier without using properties like float or position.

To center align h1(heading) using CSS flexbox, you need to simply set the display property to flex. This will make the h1 element behave like a flex container.

Now, to center it horizontally, you can set the justify-content property to center. The justify-content property is used to align flex items horizontally within their flex container.

Use the following CSS code:

h1{
    display: flex;
    justify-content: center;
}

This will produce the following output:

Center h1 using CSS flexbox

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.