Juneikerc.com

Center form with html and css

Featured image for the post: Centering HTML and CSS Form

Earlier, we learned how to center an image with CSS, and with this tutorial, you will discover how to center a form in HTML. These are two skills that all web designers and developers should master. Centering the inputs of a form uniformly can sometimes be challenging, so we will explain how to do it easily.

Let's Define the HTML Structure of Our Form

For this exercise, we will create a simple structure with a div that will act as a container and a form with three inputs.

html
<div>
<form class="form">
<input type="text" />
<input type="email" />
<input type="password" />
<button type="submit">Submit</button>
</form>
</div>
  • We have a div that wraps around the form.
  • The form element has a class 'form' that we will use to apply styles in our CSS stylesheet.
  • Then, we have three inputs and a button with typical form values.

Next, we add the CSS to align the form elements.

Adding CSS to Center the Form and Make It Responsive

css
.form {
width: 100%;
max-width: 600px;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.form input {
width: 90%;
height: 30px;
margin: 0.5rem;
}
.form button {
padding: 0.5em 1em;
border: none;
background: rgb(100, 200, 255);
cursor: pointer;
}
  • Using the class 'form,' we assign a width of 100% to the form with 'width: 100%;' so that it spans the entire width corresponding to its container div. This is primarily to ensure it occupies all available space on smaller screens.
  • We give the form a maximum width of 600px with 'max-width: 600px,' so that on larger screens, the form doesn't stretch too much and keeps its elements from taking up all the available space.
  • The rule 'margin: 0 auto;' horizontally centers the content with respect to its container. On wide screens, the form will be in the center of the element, and on narrow screens, it will occupy all available space.
  • Using flexbox, we align the elements, both the inputs and the button, one below the other and center them within the form to stack the elements vertically and center the inputs within the form.
  • Finally, we add some styles to make the inputs and the button look better.

Completing the Form and the Result on CodePen

As you can see, centering a form with CSS is very easy. You can view the entire example code below.

Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me