Vertically align an image inside a div with responsive height

后端 未结 10 1675
遇见更好的自我
遇见更好的自我 2020-11-22 02:47

I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).

10条回答
  •  悲&欢浪女
    2020-11-22 03:20

    Here's a technique that allows you to center ANY content both vertically and horizontally!

    Basically, you just need a two containers and make sure your elements meet the following criteria.

    The outher container :

    • should have display: table;

    The inner container :

    • should have display: table-cell;
    • should have vertical-align: middle;
    • should have text-align: center;

    The content box :

    • should have display: inline-block;

    If you use this technique, just add your image (along with any other content you want to go with it) to the content box.

    Demo :

    body {
        margin : 0;
    }
    
    .outer-container {
        position : absolute;
        display: table;
        width: 100%;
        height: 100%;
        background: #ccc;
    }
    
    .inner-container {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    
    .centered-content {
        display: inline-block;
        background: #fff;
        padding : 12px;
        border : 1px solid #000;
    }
    
    img {
       max-width : 120px;
    }

    See also this Fiddle!

提交回复
热议问题