Vertical centering variable height image while maintaining max-width/height

后端 未结 3 1548
无人及你
无人及你 2020-11-30 08:37

I want to center an image of unknown width/height on a page, while making sure that it shrinks if it is bigger than the page (i.e. use max-width/max-heigh

3条回答
  •  误落风尘
    2020-11-30 09:09

    This should prove to work quite well... no JavaScript necessary :)

    See the working demo on jsFiddle.

    CSS

    /* Don't Change - Positioning */
    .absoluteCenter {
     margin:auto;
     position:absolute;
     top:0;
     bottom:0;
     left:0;
     right:0;
    }
    
    /* Sizing */
    img.absoluteCenter {
     max-height:100%;
     max-width:100%;
    }
    

    HTML

    
    

    Note: This class can be used for anything quite easily. If you use this for something other than an image, make sure to add a TAG.absoluteCenter CSS rule with a max-height and max-width of your choosing (where TAG is the HTML tag you're using [e.g. div.absoluteCenter] and max-width/max-height is less than 100%).

提交回复
热议问题