How to vertically center <div> inside the parent element with CSS?

Crays picture Crays · Apr 30, 2010 · Viewed 390.8k times · Source

I'm trying to make a small username and password input box.

I would like to ask, how do you vertically align a div?

What I have is:

<div id="Login" class="BlackStrip floatright">
   <div id="Username" class="floatleft">Username<br>Password</div>
   <div id="Form" class="floatleft">
   <form action="" method="post">
      <input type="text" border="0"><br>
      <input type="password" border="0">
   </form>
   </div>
</div>

How can I make the div with id Username and Form to vertically align itself to the center? I've tried to put:

vertical-align: middle;

in CSS for the div with id Login, but it doesn't seem to work. Any help would be appreciated.

Answer

Andy E picture Andy E · Apr 30, 2010

The best approach in modern browsers is to use flexbox:

#Login {
    display: flex;
    align-items: center;
}

Some browsers will need vendor prefixes. For older browsers without flexbox support (e.g. IE 9 and lower), you'll need to implement a fallback solution using one of the older methods.

Recommended Reading