CSS Flex Box: How to vertically align “flex items” to middle without losing flex item height?

后端 未结 4 679
野性不改
野性不改 2020-12-31 11:03

Currently my \"flex\" items look like this (vertically aligned: top)...

 _____________________________________
   1

 _____________________________________
          


        
4条回答
  •  甜味超标
    2020-12-31 12:02

    To vertical align content of flexbox child, you will need to apply some other techniques.

    I believe there will be content there , wrapped in tag, You can then again use flex and set child in margin:auto; DEMO


    CSS updated :

    /* Flex Box */
     section {
        padding: 1em;
        background: black;
        display: flex;
        flex-flow: column;
        height: 100%;
        justify-content: space-around;
    }
    /* Flex Items */
     div {
        border-top: 1px solid #ccc;
        background: #f2f2f2;
        height: 25%;
        display:flex;/* be a flexbox too */
    }
    div:first-child {
        border-top: 1px solid transparent;
    }
    div:hover {
        background: white;
    }
    p { /* or any child of flex box used */
        margin:auto;/* here center/middle align */
    }
    

    HTML structure :

    
    

    1

    2

    3

    4


    Maybe a fallback with display:table , can be usefull : DEMO 2

    /* fall back IE8 ie */
    html, body, section {
        -moz-box-sizing:border-box;
        box-sizing:border-box;
        height:100%;
        width:100%;
    }
    section {
        display:table;
    }
    section > div {
        display:table-cell;
        vertical-align:middle;
    }
    
    /* Flex Box */
     section {
        padding: 1em;
        background: black;
        display: flex;
        flex-flow: column;
        height: 100%;
        justify-content: space-around;
    }
    /* Flex Items */
     section > div {
        border-top: 1px solid #ccc;
        background: #f2f2f2;
        height: 25%;
        display:flex;
    }
    section > div:first-child {
        border-top: 1px solid transparent;
    }
    section > div:hover {
        background: white;
    }
    p {
        margin:auto;
    }
    

提交回复
热议问题