vertical-align with Bootstrap 3

后端 未结 25 2392
庸人自扰
庸人自扰 2020-11-21 05:34

I\'m using Twitter Bootstrap 3, and I have problems when I want to align vertically two div, for example — JSFiddle link:

25条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 06:01

    Update 2020

    I know the original question was for Bootstrap 3, but now that Bootstrap 4 has been released, here is some updated guidance on vertical center.

    Important! Vertical center is relative to the height of the parent

    If the parent of the element your trying to center has no defined height, none of the vertical centering solutions will work!

    Bootstrap 4

    Now that Bootstrap 4 is flexbox by default there are many different approaches to vertical alignment using: auto-margins, flexbox utils, or the display utils along with vertical align utils. At first "vertical align utils" seems obvious, but these only work with inline and table display elements. Here are some Bootstrap 4 vertical centering options..


    1 - Vertical Center Using Auto Margins:

    Another way to vertically center is to use my-auto. This will center the element within its container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

    Card

    Bootstrap 4 - Vertical center using auto-margins Demo

    my-auto represents margins on the vertical y-axis and is equivalent to:

    margin-top: auto;
    margin-bottom: auto;
    

    2 - Vertical Center with Flexbox:

    Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

           
    Center
    Taller

    or, use align-items-center on the entire .row to vertically center align all col-* in the row...

           
    Center
    Taller

    Bootstrap 4 - Vertical center different height columns Demo


    3 - Vertical Center Using Display Utils:

    Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

    I am centered vertically

    Bootstrap 4 - Vertical center using display utils Demo

    Also see: Vertical Align Center in Bootstrap 4


    Bootstrap 3

    Flexbox method on the container of the item(s) to center:

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

    Transform translateY method:

    .transform-center-parent {
        position: relative;
        transform-style: preserve-3d;
    }
    
    .transform-center {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
    

    Display inline method:

    .display-inline-block {
        display: inline;
    }
    .display-inline-block > div {
        display: inline-block;
        float: none;
        vertical-align: middle;
    }
    

    Demo of Bootstrap 3 centering methods

提交回复
热议问题