How to vertically center divs?

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.


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 (eg IE 9 and lower), you'll need to implement a fallback solution using one of the older methods.

Recommended Reading

  • Browser support
  • A Guide to Flexbox
  • Using CSS Flexible Boxes

  • You can vertically align a div in another div. See this example on JSFiddle or consider the example below.

    HTML

    <div class="outerDiv">
        <div class="innerDiv"> My Vertical Div </div>
    </div>
    

    CSS

    .outerDiv {
        display: inline-flex;  // <-- This is responsible for vertical alignment
        height: 400px;
        background-color: red;
        color: white;
    }
    
    .innerDiv {
        margin: auto 5px;   // <-- This is responsible for vertical alignment
        background-color: green;   
    }
    

    The .innerDiv 's margin must be in this format: margin: auto *px;

    [Where, * is your desired value.]

    display: inline-flex is supported in the latest (updated/current version) browsers with HTML5 support.

    It may not work in Internet Explorer :P :)

    Always try to define a height for any vertically aligned div (ie innerDiv) to counter compatibility issues.


    This can be done with 3 lines of CSS and is compatible back to (and including) IE9:

    .element {
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
    

    Example: http://jsfiddle.net/cas07zq8/

    credit

    链接地址: http://www.djcxy.com/p/7146.html

    上一篇: 居中图像垂直和水平

    下一篇: 如何垂直居中divs?