How to center a span containing an image in a div

后端 未结 6 1669
傲寒
傲寒 2021-01-16 04:17

I have a main div (#homeGallery), in which i have a span(.imgClass) that is used to load one of a list of images. I need the image to be centered not only vertically but ho

6条回答
  •  时光说笑
    2021-01-16 04:56

    This is my prefered method:

    HTML

    You can use whatever img you want here

    CSS

    #homeGallery{
        height: 400px;
        border: 1px solid #333;
        text-align: center;
    }
    #homeGallery:before{
        content: '';
        height: 100%;
        vertical-align: middle;
        display: inline-block;
    }
    
    .imgClass{
        display: inline-block;
        vertical-align: middle;
        text-align: left;
        background-color: blue;
    }
    

    jsfiddle here.

    The good side is that this is 100% css-based vertical alignment. You don't have to worry about screen size or DOM size change.

    The cons is that it doesn't work on IE7 or lower.

提交回复
热议问题