CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

后端 未结 2 1200
终归单人心
终归单人心 2020-12-08 04:06

With only the parent div and the child img elements as demonstrated below how do I vertically and horizontally center the

相关标签:
2条回答
  • 2020-12-08 04:33

    Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

    <div style="display: flex;">
    <div style="display: flex;">
     <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
    </div>
    </div>
    

    If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

    align-items: center;
    display: flex;
    justify-content: center;
    
    0 讨论(0)
  • 2020-12-08 04:37

    Just add the following rules to the parent element:

    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center; /* align vertical */
    

    Here's a sample demo (Resize window to see the image align)

    Browser support for Flexbox nowadays is quite good.

    For cross-browser compatibility for display: flex and align-items, you can add the older flexbox syntax as well:

    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    
    0 讨论(0)
提交回复
热议问题