Background-size cover to img tag

后端 未结 2 1001
春和景丽
春和景丽 2020-12-20 09:30

html

2条回答
  •  半阙折子戏
    2020-12-20 09:40

    Solution #1 - The new object-fit property (Browser support)

    Just set object-fit: cover; on the img .

    img {
      display: block;
      width: 200px;
      height: 100px;
      object-fit: cover;
    }

    You can read more about this new property in this webplatform article.

    From the above article - regarding the 'cover' value:

    The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible.

    Also, here is a fiddle from the above article which demonstrates all the values of the object-fit property.

    Solution #2 - Replace the img with a background image with css

    img {
      position: relative;
      width: 0;
      height: 0;
      padding: 50px 100px;
      background: url(http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg) no-repeat;
      background-size: cover;
    }

提交回复
热议问题