CSS image resize percentage of itself?

前端 未结 11 2163
执念已碎
执念已碎 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:18

    HTML:

    
        
    
    

    CSS:

    span {
        display: inline-block;
    }
    img {
        width: 50%;
    }
    

    This has got to be one of the simplest solutions using the container element approach.

    When using the container element approach, this question is a variation of this question. The trick is to let the container element shrinkwrap the child image, so it will have a size equal to that of the unsized image. Thus, when setting width property of the image as a percentage value, the image is scaled relative to its original scale.

    Some of the other shrinkwrapping-enabling properties and property values are: float: left/right, position: fixed and min/max-width, as mentioned in the linked question. Each has its own side-effects, but display: inline-block would be a safer choice. Matt has mentioned float: left/right in his answer, but he wrongly attributed it to overflow: hidden.

    Demo on jsfiddle


    Edit: As mentioned by trojan, you can also take advantage of the newly introduced CSS3 intrinsic & extrinsic sizing module:

    HTML:

    CSS:

    figure {
        width: intrinsic;
    }
    img {
        width: 50%;
    }
    

    However, not all popular browser versions support it at the time of writing.

提交回复
热议问题