How to center a span containing an image in a div

后端 未结 6 1671
傲寒
傲寒 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:41

    Here's a Fiddle

    #homeGallery .imgClass {
      position: relative;
      width: 200px;
      height: 200px;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -100px;
    }
    

    If you dont know the image width & height than you could use jQuery solution

    $(function() {
    
      var imgW = $('.imgClass').outerWidth(),
          imgH = $('.imgClass').outerHeight();
    
      $('.imgClass').css({ marginLeft: - imgW / 2 + 'px', marginTop: - imgH / 2 + 'px' });
    
    });
    

    and this CSS

    #homeGallery .imgClass {
      position: relative;
      top: 50%;
      left: 50%;
    }
    

提交回复
热议问题