How to center an element vertically and horizontally with CSS?


To center an element vertically and horizontally with CSS, use the justify-content and align-items properties. We have used flex in our examples.

The Justify-content Property

In CSS, the justify-content property is used to align the items horizontally. The syntax of CSS justify-content property is as follows −

Selector {
   display: flex;
   justify-content: /*value*/
}

The following are the values −

  • flex-start − The flex items are positioned at the start of the container. This is the Default value.

  • flex-end − The flex items are positioned at the end of the container

  • center − The flex items are positioned in the center of the container

  • space-between − The flex items will have space between them

  • space-around − The flex items will have space before, between, and after them

  • space-evenly − The flex items will have equal space around them

The Align-items Property

In CSS, the align-items property is used to set the default alignment for flex-items in a flexbox. It aligns the items vertically.

Syntax

The syntax of CSS align-items property is as follows −

Selector {
   display: flex;
   justify-content: /*value*/
}

The following are the values −

  • stretch − The flex-items are stretched to fit the container

  • center − The flex-items are positioned at the center of the containe

  • flex-start − The flex-items are positioned at the beginning of the container

  • flex-end − The flex-items are positioned at the end of the container

Create an Element

Let’s say we are aligning an element <h2>. The <h2> element is used to create a heading n a web page −

<h2>This text is centered vertically and horizontally both</h2>

Set the Element Inside a div

To center align a button, set the button element inside a div −

<div class="centered">
   <h2>This text is centered vertically and horizontally both</h2>
</div>

Style the div and Center Align

To center align vertically, use the align-items property. To center align horizontally, use the justify-content property. Set center for both the values −

.centered {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 200px;
   border: 3px solid rgb(0, 70, 128);
}

Example

Let us see the example

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .centered {
         display: flex;
         justify-content: center;
         align-items: center;
         height: 200px;
         border: 3px solid rgb(0, 70, 128);
      }
   </style>
</head>
<body>
   <h1>Centering Example</h1>
   <div class="centered">
      <h2>This text is centered vertically and horizontally both</h2>
   </div>
</body>
</html>

Updated on: 16-Nov-2023

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements