DEV Community

Amaan Shaikh
Amaan Shaikh

Posted on

How to center an element in HTML using CSS Flexbox and CSS grid.

I have seen many developers struggling to center an element on the webpage using CSS. There are many applications where we want our HTML element to be at the center of the page. Usually, login or register forms are kept at the center of the webpage for a better user experience.

In this article, I will help you with two ways to place an element at the center of the page by using CSS Flexbox and CSS grid.

Consider an example where we just have a single form element in our HTML page and we have to center the same. The HTML code for this will be as below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Center Form Element</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <form>
      <h4>Login Form</h4>
      <label for="email">Email ID:</label>
      <input type="text" placeholder="Enter your Email" name="email" id="email"/>
      <label for="password">Password:</label>
      <input type="password" placeholder="Enter your your password"name="password"/>
      <button>Login</button>
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Considering our body tag as a parent and form tag as a child we can center the form element by adding either of the following code snippets in our styles.css file

Centering an element using CSS Flexbox

body{
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Centering an element using CSS Grid

body {
  display: grid;
  place-items: center;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Please note height: 100vh is given to make sure that the body is taking the full height of the webpage.

Happy Reading!

Top comments (3)

Collapse
 
colinkiama profile image
Colin Kiama

I don’t know how I was living before learning about flexbox 🤣

Collapse
 
amaan56 profile image
Amaan Shaikh

I used to use margin:auto property but this would only align the item horizontally, for vertical alignment I used to play with margin and padding values until I get the right alignment.

Collapse
 
jlrxt profile image
Jose Luis Ramos T.

Gracias soy uno de los que aún sigue batallando. Lo pondré en práctica. Muy útil gracias por compartir.