How to center div that contains an image within a div?

前端 未结 3 1249
我在风中等你
我在风中等你 2020-12-19 17:55

I need to center a image inside a div both vertically and horizontally. I am using the display inline-block property.

HTML

3条回答
  •  死守一世寂寞
    2020-12-19 18:41

    This approach works perfectly for dynamic content of unknown dimensions.

    jsFiddle example

    Basically, we are using vertical-align:middle for vertical centering, and text-align:center for horizontal centering. In order for vertical-align:middle to work on a div, we need to set the parent elements to display:table, and the targeted child div to display:table-cell. Sure you could achieve such centering with absolute positoning, however, that would require you to know the dimensions of the img. This approach works for unknown dimensions.

    HTML

    CSS

    html, body {
        height:100%;
        width:100%;
        margin:0px;
    }
    .container {
        display:table;
        vertical-align:middle;
        text-align:center;
        height:100%;
        width:100%;
    }
    .box {
        display:table-cell;
        vertical-align:middle;
    }
    

提交回复
热议问题