Html element is not vertically centered with flex

2020-04-18 07:23发布

问题:

Thats my fiddle: http://jsfiddle.net/atav8vzz/4/

Why is the html element with class "vertical-align" not vertically centered?

<div class="container">
          <div class="row">
            <div style="background:green;" class="col-xs-4">             
              <h3 class="text-center">Type 1</h3>            

            </div>

            <div style="background:red;" class="col-xs-4">             
              <h3 class="text-center vertical-align">Type 2</h3> 

            </div>

            <div style="background:blue;" class="col-xs-4">            
                <h3 class="text-center">Type 3</h3>            

            </div>
          </div>
        </div>

.vertical-align {
        display: ms-flex;
        display: flex;
        align-items: center;
    }

回答1:

I guess it depends what you're trying to achieve here. align-items does so vertically. Where as justify-content does so horizontally.

See this example. I have given the <h3> height, to illustrate that it is centred vertically.



回答2:

Just add justify-content: center; to your code:

.vertical-align {
    display: ms-flex;
    display: flex;
    align-items: center;
    justify-content: center;  
}