Signup/Sign In
PUBLISHED ON: AUGUST 19, 2021

How to horizontally center an element in HTML?

Aligning an element is important on the web page. The center alignment plays an important role while website designing. The element in HTML can be horizontally center-aligned using various ways.

Here we will list out possible solutions to horizontally center the element in HTML.

Using margin and width to horizontally center align element

Here, we have used the margin: auto and set width: 400px to HTML element to center align them horizontally within the page. Here is an example to show the center alignment of elements using margin and width.

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML </title>
<style>
  h2 , p {
  width: 400px;
  margin: auto;
}
</style>
</head>
<body>  
   <h2>Horizontally Center align text</h2>
   <p> Here we have center aligned the whole text in the document </P>
</body>
</html>

Output

So in the output, we can see that both the heading and paragraph are center-aligned.

center align

Horizontally center aligning element using CSS property

The CSS property which can be used to horizontally center align the element is text-align: center. So let's use this property to center align our HTML element.

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML </title>
<style>
  h2 , p {
  text-align: center;
}
</style>
</head>
<body> 
   <h2>Horizontally Center align text</h2>
   <p> Here we have center aligned the whole text in the document </P>
</body>
</html>

Output

Here is the output of the above code where we can successfully center align the heading and paragraph.

center align using CSS

Horizontally center align using CSS display property

There is yet another CSS property that can be used to horizontally center align the element in HTML. Use display: table property to center align the element. Here is an example of this.

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML </title>
<style>
  h2 , p {
  display: table;
  margin: auto;
}
</style>
</head>
<body>  
   <h2>Horizontally Center align text</h2>
   <p> Here we have center aligned the whole text in the document </P>
</body>
</html>

Output

In the output, we can see that the elements had been successfully center-aligned.

using display

Conclusion

Here, we have used some approaches to horizontally center align the element in HTML. Combine width and margin or use the CSS align property or use display property to align items centrally.



About the author: