How do I resize an image while keeping the aspect ratio in CSS?

后端 未结 4 1780
半阙折子戏
半阙折子戏 2020-12-16 10:17

I have a large image. I want to display it on its on own a web page, and when doing this without any CSS it fills the whole page and is too big to display at once (scroll ba

4条回答
  •  一整个雨季
    2020-12-16 10:23

    You can use a div with background-image and set background-size: contain:

    div.image{
        background-image: url("your/url/here");
        background-size:contain;
        background-repeat:no-repeat;
        background-position:center;
    }
    

    Now you can just set your div size to whatever you want and not only will the image keep its aspect ratio it will also be centralized both vertically and horizontally. Just don't forget to set the sizes on the css since divs don't have the width/height attribute on the tag itself.

    The background-size property is ie>=9 only though.

提交回复
热议问题