Use object-fit to solve the problem that the size of the picture does not conform to the width and height of the parent container, and it must be displayed reasonably

Images of different sizes should be displayed in the project, but the size of the parent container is fixed and should be displayed in it reasonably. At this time, the object-fit attribute is needed to specify how the content of the element should adapt to the height and width of the specified container.

grammar

object-fit: fill|contain|cover|scale-down|none;
  1. fill default, does not guarantee to maintain the original ratio, the content is stretched to fill the entire content container.
  2. contain maintains the original size ratio. The content is scaled.
  3. cover maintains the original size ratio. However, some content may be cut.
  4. none retains the length and width of the original element content, which means the content will not be reset.
  5. scale-down maintains the original size ratio. The size of the content is the same as either none or contain, whichever of the two results in a smaller object size.

html part

<div class="image-item" >
    <div class="img-wrap">
         <img :src="item.imgUrl" alt="" class="img">
     </div>
</div>

css part

.img-wrap{
        height: 200px;
        width: 100%;
        margin: 0 auto 12px;
        padding: 20px;
        box-shadow: inset 0 0 10px 2px #003e73;

        &:hover {
            box-shadow: inset 0 0 10px 2px #57fac9;
        }
        .img{

            width: 100%;
            height: 100%;
            // object-fit: contain;
            // object-fit: cover;
            // object-fit: fill;
            // object-fit: none;
            object-fit: scale-down;
        }
    }
  
}

Display of results

insert image description here

Guess you like

Origin blog.csdn.net/qq_42563079/article/details/126600138