Centering image inside a div using CSS instead of jquery

后端 未结 4 1487
滥情空心
滥情空心 2021-01-19 17:33

I\'m trying to fit any sized image inside a (always) square div, and retain the aspect when the size of the parent div changes. Here\'s what I\'m doing:

CSS:

<
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 17:49

    The background solution that others have posted was my initial thought, but if you want to still use images then you could do the following:

    CSS:

    .photo_container {
        width: 250px;
        height: 250px;
        overflow: hidden;
        border-style: solid;
        border-color: green;
        float:left;
        margin-right:10px;
        position: relative;
    }
    
    .photo_container img {
        min-width: 100%;
        min-height: 100%;
        position: relative;
        top: 50%;
        left: 50%;
        transform: translateY(-50%) translateX(-50%);
    }
    

    HTML:

    
    
    
    

    This will make any image inside to be either 100% high or 100% wide, depending on the shortest attribute, and centralise them horizontally and vertically.

    Edit

    It's worth noting that transform is not supported in IE8 or Opera Mini - http://caniuse.com/#feat=transforms2d

提交回复
热议问题