Home > Article > Web Front-end > How to make images adapt to the size of div using css
You can make the image adapt to the Div size by using the object-fit attribute in CSS: specify the width and height for the Div container and specify the object-fit attribute for the image, and the value is contain, cover or scale-down according to Need to add other CSS styles, such as margins or alignment
CSS adaptive image
How to make Are images adaptive to Div size?
You can make the image adapt to the Div size by using the object-fit
attribute in CSS. This property specifies how the image is fit inside the Div, ensuring that the image always maintains the best proportions within the Div container.
Steps:
Specify the object-fit
attribute for the image: Add the object-fit
attribute for the image and set its value to the following One of the options:
contain
: Scale the image to be fully visible while maintaining the original aspect ratio of the image. cover
: Scale the image to completely fill the Div, may need to be cropped to maintain aspect ratio. scale-down
: Only scale down the image (not enlarge it) to fit the size of the Div. Example:
<code class="css">/* 设置 Div 大小 */ div { width: 200px; height: 150px; } /* 设置图片样式 */ img { object-fit: contain; /* 或 cover 或 scale-down */ }</code>
Note:
object-fit
attribute may not be supported in older browsers, but you can use object-position
and background-size
etc. Alternative ways to achieve a similar effect. The above is the detailed content of How to make images adapt to the size of div using css. For more information, please follow other related articles on the PHP Chinese website!