How to set an image's width and height without stretching it?

前端 未结 12 1549
南旧
南旧 2020-11-28 05:22

If I have:

#logo {
    width: 400px;
    height: 200px;
}

then


相关标签:
12条回答
  • 2020-11-28 05:28

    2017 answer

    CSS object fit works in all current browsers. It allows the img element to be larger without stretching the image.

    You can add object-fit: cover; to your CSS.

    0 讨论(0)
  • 2020-11-28 05:34

    you can try setting the padding instead of the height/width.

    0 讨论(0)
  • 2020-11-28 05:34

    What I can think of is to stretch either width or height and let it resize in ratio-aspect. There will be some white space on the sides. Something like how a Wide screen displays a resolution of 1024x768.

    0 讨论(0)
  • 2020-11-28 05:39

    Do I have to add an encapsulating <div> or <span>?

    I think you do. The only thing that comes to mind is padding, but for that you would have to know the image's dimensions beforehand.

    0 讨论(0)
  • 2020-11-28 05:40

    Make a div and give it a class. Then drop a img in it.

    <div class="mydiv">
    
    <img src="location/of/your/image" ></img>
    
    </div>
    

    Set the size of your div and make it relative.

        .mydiv {
            position: relative;
            height:300px;
            width: 100%;
            overflow: hidden;
        }
    

    then style your image

    img {
        width: 100%;
        height: auto;
        overflow: hidden;
    }
    

    Hope that helps

    0 讨论(0)
  • 2020-11-28 05:41
    #logo {
        width: 400px;
        height: 200px;
    
        /*Scale down will take the necessary specified space that is 400px x 200px without stretching the image*/
        object-fit:scale-down;
    }
    
    0 讨论(0)
提交回复
热议问题