This guide will demonstrate how to center h1 in CSS.
How to Center h1 in CSS?
To center the h1, we will use the following CSS properties:
Let’s get started with method one!
Method 1: Use text-align Property to Center h1 in CSS
In CSS, the “text-align” property is utilized to set the text of HTML elements to the left, center, or right horizontally. Generally, we can say that this property is very useful for text alignment.
Here look at the example below to understand how the text-align property works.
Example
We have a hearing on the web page currently aligned to the left side by default. Let’s get this heading in the center:
In the HTML file, set the <h1> tag in the body section and add some text to it.
HTML
In the CSS file, we will utilize the “text-align” property and set its value to the “center”. This will align the heading h1 to the center.
CSS
text-align: center;
}
Save the code and open it in the browser:
As you can see, we have successfully centered the h1 using CSS text-align property.
Method 2: Use display Property to Center h1 in CSS
When it comes to defining the HTML element behavior, the “display” property is used. This property has some useful values, such as flex and block. Moreover, the flexible behavior of elements is a result of flex value, and the block behavior of elements is a result of block value.
Example
Firstly, specify the “display” property and its value to the “flex”. This will make the heading element flexible. In the next step, use the “justify-content” property with the value “center” to set the heading in the center.
CSS
display: flex;
justify-content: center;
}
Output
The heading h1 is aligned to center successfully.
Method 3: Use position Property to Center h1 in CSS
This “position” property is self-explanatory; it decides how an HTML element will be placed at some position. Combining this property with other CSS properties will result in accomplishing the desired objective, which is setting heading h1 in CSS.
Example
To center the h1, the “position” property can be utilized with the value “relative”. This will rearrange the element’s normal position. Now, use the “left” property, and set its value to “40%” to create a space from the left side will be created, and our heading will be aligned to the center.
CSS
position: relative;
left: 40%;
}
Output
We have explained the easiest methods to center h1 in CSS.
Conclusion
To center h1, the CSS “text-align”, “display”, or “position” properties can be utilized. For the mentioned purpose, the text-align property will be used with the “center”, the display property will be used with the “flex” value, and we will set the position property value “relative” to get the desired result. This article has covered how to center h1 using different CSS properties.