CSS image resize percentage of itself?

前端 未结 11 2100
执念已碎
执念已碎 2020-11-28 20:46

I am trying to resize an img with a percentage of itself. For example, I just want to shrink the image by half by resizing it to 50%. But applying width: 50%; w

11条回答
  •  离开以前
    2020-11-28 21:41

    Actually most of the answers here doesn't really scale the image to the width of itself.

    We need to have a width and height of auto on the img element itself so we can start with it's original size.

    After that a container element can scale the image for us.

    Simple HTML example:

    And here are the CSS rules. I use an absolute container in this case:

    figure {
        position: absolute;
        left: 0;
        top: 0;
        -webkit-transform: scale(0.5); 
        -moz-transform: scale(0.5);
        -ms-transform: scale(0.5); 
        -o-transform: scale(0.5);
        transform: scale(0.5);
        transform-origin: left;
    } 
    
    figure img {
        width: auto;
        height: auto;
    }
    

    You could tweak the image positioning with rules like transform: translate(0%, -50%);.

提交回复
热议问题