How to center an input field using CSS?

The easiest way to center an input field in CSS is to put the input element inside a div element and then apply text-align: center; on this parent div element.

Here is a working example of it:

Example:

div{
   text-align: center;
}

Center an input field using margin: auto

An interesting use case of the margin property is that it can magically center things within their container.

All you need to do is apply margin: auto; on the element that you want to center. But there is one important thing that is to be kept in mind is that if the element is not a block-level element, applying margin: auto; will not center the element.

In that case, you have to explicitly make the element a block-level element by applying display: block; on it.

Here is a complete example that centers the input element using margin: auto;

Example:

input{
    margin: auto;
    display: block;
}

Center an input field using CSS Grids

CSS grids are always the best alternatives in terms of aligning items both horizontally as well as vertically.

To center an input field using CSS grids all you need to do is put the input element inside a div and make this div element a grid container by applying display: grid; on it.

Now if you want to center the input element horizontally use justify-content: center; and to center vertically use align-items: center;

Here is a working example of it:

Example:

div{
   display: grid;
   justify-content: center;
}