Explain Codes LogoExplain Codes Logo

Css: How to align vertically a "label" and "input" inside a "div"?

html
responsive-design
css
layout
Anton ShumikhinbyAnton Shumikhin·Jan 13, 2025
TLDR

Use flexbox for vertical alignment. Set the div container to display: flex and align-items: center:

<div style="display: flex; align-items: center;"> <label for="name">Name:</label> <input type="text" id="name"> </div>

Both label and input will be centered regardless of their height.

The Flexbox approach for advanced vertical alignment

When you've got the basic flexbox alignment nailed down, and you're ready to dive deep into controlling your layout, try these professional techniques.

Fine-tuning with Flexbox

Flexbox lets you control not just the group as a whole, but each individual element's vertical alignment:

label { align-self: center; /* Gives the label control of its own destiny */ } input { align-self: center; /* Input also steps up */ }

You can combine this technique with justify-content for granular control over horizontal space as well:

div { display: flex; align-items: center; justify-content: space-between; /* Decides how to split unused horizontal space */ }

The legendary table-cell method

display: table-cell might not be the trendy kid on the block, but it still has its uses:

div { display: table-cell; vertical-align: middle; /* The old school way to get things around the middle */ }

However, flexbox is generally the life of the party when it comes to responsive designs.

Getting your heights fair and even

Alignment doesn't just happen. Ensure a consistent div height:

div { height: 50px; /* Keeps the div at a consistent height */ }

Adding style to make a statement

Use a simple background color and adjust the position property to make your layout intuitive:

div { /* ... */ background-color: #f0f0f0; /* Easy on the eyes */ padding: 10px; /* Adds a dash of space in and around */ }

Quick and easy inline-block alignment

As a quick-fix, setting line-height equal to the div's height can do the trick:

label, input { display: inline-block; line-height: 50px; /* Matches the div height for perfectly centered alignment */ }

The responsive power of Flexbox

Flexbox is your best friend for responsive designs:

@media (max-width: 600px) { div { flex-direction: column; /* Stack fields for smaller screens */ } label, input { width: 100%; /* Full width for better thumb scrolling */ } }

Wrapped up for free structure

Wrapping your input with the label can give your structure a little boost:

<label for="name">Name: <input type="text" id="name"></label>

The perfect margin for the perfect fit

Manage the margin on inputs for some fine vertical alignment:

input { margin-top: 5px; /* Nobody is perfect. Sometimes, you need a little push. */ }

Have you checked it on IE?

Don't forget to test your design in various browsers to ensure it works everywhere.