Centering things in HTML and CSS is not a new frontend problem. However, there are multiple solutions to Center a Heading in HTML.
In this tutorial, I’ll share some of the easiest ways to center a heading and also how to center text in HTML-CSS.
So, let’s begin-
How to Center a Heading in HTML
In HTML, there are 6 levels of headings. These are from <h1> Heading 1 (The largest one)</h1> to <h6>Heading 6 (The smallest one)</h6>. You can bring all the heading texts into the center.
BTW, You may already know that, HTML headings are block-level elements. It simply means, They eat up all the space towards their left and right, and no other element can easily span with them.
Here is How to center a <h1>, <h2>, … , <h6> Heading elements-
-
Using CSS text alignment:
<style> h1{ text-align:center; } </style> <body> <h1>Here's a Heading in HTML</h1> </body>
You can also do it with inline CSS styling-
<h1 style="text-align:center;">Here's a Heading in HTML</h1>
Output- when you’ll run it, you will see something like the above diagram.
In the above code snippet, we’ve taken only the <h1> heading tag, but the CSS center alignment property will perfectly work with all other heading tags of HTML.
Here’s the code snippet with the desired result that shows: How to center Heading in HTML-
See the Pen
Centering Heading in HTML by Shubham (@ShubhamKLogic)
on CodePen.
How to put Text in the middle of a page – HTML
So, far we have learned to center headings in HTML, but what if you need to center inline elements horizontally.
Here’s the solution to do it-
.center-childrens { text-align: center; }
See the Pen
Centering Text in HTML-CSS by Shubham (@ShubhamKLogic)
on CodePen.
In the above example to put text in the middle, we have used same CSS property and value i.e. text-align: center; The CSS alignment property can also hold different other values, such as-
text-align:
What We Learned?
So far, we have learned How to center a Heading and text in HTML. We’ve also learned how to use align text left, center, right with inline CSS.
Must read similar useful articles like Center a Heading-
- Full list of HTML and CSS – Helpful articles
- HTML Interview Questions and Answers – For Freshers
- HTML Interview Questions and Answers – For Intermediates