CSS Display an Image Resized and Cropped

前端 未结 19 1862
时光取名叫无心
时光取名叫无心 2020-11-22 08:09

I want to show an image from an URL with a certain width and height even if it has a different size ratio. So I want to resize (maintaining the ratio) and then cut the imag

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 08:47

    With CSS3 it's possible to change the size of a background-image with background-size, fulfilling both goals at once.

    There are a bunch of examples on css3.info.

    Implemented based on your example, using donald_duck_4.jpg. In this case, background-size: cover; is just what you want - it fits the background-image to cover the entire area of the containing

    and clips the excess (depending on the ratio).

    .with-bg-size {
      background-image: url('https://i.stack.imgur.com/wPh0S.jpg');
      width: 200px;
      height: 100px;
      background-position: center;
      /* Make the background image cover the area of the 
    , and clip the excess */ background-size: cover; }
    Donald Duck!

    css3 background-image background-size

提交回复
热议问题