Center an Image vertically and horizontally using CSS

前端 未结 10 1075
遥遥无期
遥遥无期 2020-11-30 08:12

How do I vertically and horizontally center an image when I do not know the size of it? I asked this question and someone suggested using a table. This isn\'t the first time

10条回答
  •  佛祖请我去吃肉
    2020-11-30 08:25

    With a table:

    The 400 is just something I picked. You will need to define a height on table so it is taller than your image.

    A jquery solution would be good if you wanted to try and use divs and junk, but if you don't care you don't care. You also have to rely on JS being turned on.

    HTML:

    JS:

    $('#imgContainer > img').each(function(){
        //get img dimensions
        var h = $(this).height();
        var w = $(this).width();
    
        //get div dimensions
        var div_h =$('#imgContainer').height();
        var div_w =$('#imgContainer').width();
    
        //set img position
        this.style.top = Math.round((div_h - h) / 2) + 'px';
        this.style.left = '50%';
        this.style.marginLeft = Math.round(w/2) + 'px';
    });
    

提交回复
热议问题