CSS - how to pave the whole div when the image is tiled and full, and the image width is smaller than the div

Question: Suppose the width of a div box is 1000px; The height is 800px; There is an img image in the div. The image width is

Question:

Suppose that the width of a div box is 1000px; The height is 800px; There is an img image in the div. The image width is 700px and the height is 560px. How to spread the image throughout the div


method:

 img{     width:100%;     height:100%;     object-fit: cover; }


object-fit It is an attribute in CSS3, used to set elements (usually <img> Or <video> )How it is displayed in the container. It has the following optional values:

  • fill : When the element size does not match the container, the element will be stretched to fill the entire container. This may cause the aspect ratio of the element to be changed.

  • contain : When the element size is larger than the container, the element will be scaled to fit the container and maintain its original width height ratio. When the element size is smaller than the container, the element is displayed in its original size.

  • cover : When the element size is smaller than the container, the element will be enlarged to fill the container and maintain its original width height ratio. When the element size is larger than the container, the element will be trimmed to fit the container.

  • none : The element is displayed in its original size, ignoring the size of the container.

  • scale-down : When the element size is larger than the container, the element will shrink to fit the container and maintain its original width height ratio. When the element size is smaller than the container, the element will be displayed in its original size (equivalent to none )。

Sample code:

 .container {   width: 200px;   height: 200px;   border: 1px solid black; }   .image {   width: 100%;   height: 100%;   object-fit: contain; }

In the above code, the container .container The width and height of the image are both 200 pixels .image Is set to fill the entire container and maintain the original aspect ratio, using object-fit: contain; To achieve.

comment