How to center an element vertically and horizontally with CSS?

In this tutorial, we will learn how to center an element vertically and horizontally using CSS? By Apurva Mathur Last updated : July 25, 2023

Centering an element vertically and horizontally can be easily achieved by using three basic but important properties of CSS.

Centering an element vertically and horizontally with CSS

To center an element vertically and horizontally, you can use the CSS properties display, justify-content, and align-items with the values "flex", "center", and "center" respectively. Whether you want to center any element or you want to center any text inside the element it is always considered a good practice when all these three properties are used. The display-flex property allows easy growth or shrinking of the element. The other two properties are used for the proper alignment.

CSS to center an element vertically and horizontally

Copy and use the following CSS to center an element vertically and horizontally. Here, we are applying this CSS to div elements.

div {
  /* Main properties to center vertically and horizontally*/
  display: flex;
  justify-content: center;
  align-items: center;
  /* Other properties to style div*/
  height: 550px;
  background-color: lightsalmon;
  border: 5px solid black;
  color: white;
}

Example to center an element vertically and horizontally using CSS

In this example, we have a div and writing some content in it. With the help of CSS, we are centering div vertically and horizontally.

<!DOCTYPE html>

<html>
   <head>
      <style>
         div{
         display: flex;
         justify-content: center;
         align-items: center;
         height: 550px;
         background-color: lightsalmon;
         border:5px solid black;
         color: white;
         }
      </style>
   </head>
   
   <body style="font-family: 'Bell MT';font-size: 80px;font-weight: bolder">
      <div>
         <p>HI Include Helps welcomes you all</p>
      </div>
   </body>
   
</html>

The output of the above example is:

Example: Center an element vertically and horizontally

Example code explanation

In the above code, I've taken a div container and I've specified all the properties which we discussed above, with this, I've also provided the height of the div as the button is inside the div so it is important to provide the height of the div. After that I've just taken the paragraph element inside the div tag in which I have written the text (you can use heading tags, span tags etc., in spite of the paragraph tag). The only thing which is important here is to give specify all these three properties display:flex, justify-content:center, align-items:center.

CSS Examples »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.