How to Center a HTML Form in CSS

The best way to center a form horizontally in HTML and CSS is by using CSS flexbox. It is responsive and works well on mobile, tablet and desktop view.

Previously, we used to rely on methods that seemed like some CSS hacks. CSS flexbox came to solve such problems.

How to center a HTML form in a Div horizontally using CSS Flexbox

You need a form with it elements already created. For my case I will use.

<form>
  <label>Email:</label>
  <input type="email" name="email" placeholder="Email">
  <input type="submit">
</form>

Uncentered HTML form

Wrap your form element in a div tag.

<div>
  <form>
    <label>Email:</label>
    <input type="email" name="email" placeholder="Email">
    <input type="submit">
  </form>		
</div>

Add a class to the div html tag that will be used to center the form.

<div class="form-center">
  <form>
    <label>Email:</label>
    <input type="email" name="email" placeholder="Email">
    <input type="submit">
  </form>		
</div>

Advertisement

Add the CSS flexbox to the class form-center.

.form-center {
  display:flex;
  justify-content: center;
}

centered HTML form

Test your form. It should be centered. You can also check the results of centering using CSS flexbox.

Full Centered Form HTML CSS Flexbox Code

<div class="form-center">
  <form>
    <label>Email:</label>
    <input type="email" name="email" placeholder="Email">
    <input type="submit">
  </form>		
</div>
.form-center {
  display:flex;
  justify-content: center;
}

How to center a form horizontally using CSS margin

.form-center {
  width:400px;
  margin: 0 auto;
}

This was by far the most used method in centering block level elements like forms in HTML and CSS.

How to center a form horizontally using absolute CSS positioning

You wrap a div with a class of form-center around the form element.

<div class="form-center">
  <form>
    <label>Email:</label>
    <input type="email" name="email" placeholder="Email">
    <input type="submit">
  </form>
</div>

You give the div tag relative positioning and set its width and height. You have to set the width and height, otherwise this will not work.

.form-center {
  position: relative;
  width:100%;
  height:10em;
}

Now you can add the CSS to position the form at the center of your container.

.form-center form {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.