Home >Web Front-end >Front-end Q&A >How to achieve non-stretching effect of images in css
In CSS, you can set the properties of the background image to achieve the effect of non-stretching of the image. We usually use the following two methods:
Method 1: background-size
Use the background-size attribute to define the size of the background image. You can specify the width and height of the background image, or you can use cover or contain to adapt to the background image size. When using cover, the background image is stretched to fill the entire width and height of the element, but does not deform. When using contain, the background image will maintain its original size within the element while filling the element to its fullest extent.
For example, the following code can set the background image to a fixed size without stretching:
div { background-image: url("example.jpg"); background-size: 300px 200px; }
Method 2: background-position
Use background-position The attribute can set the position of the background image, where the value can be a specific pixel value or a relative position, such as center, top, etc. If we position the background image in the center of the element, the background image will not stretch no matter how the element changes size.
For example, the following code sets the background image to the center of the element:
div { background-image: url("example.jpg"); background-position: center center; background-repeat: no-repeat; }
Use the above two methods to achieve a non-stretched background image in CSS. You can choose the specific method that suits you based on the actual situation.
The above is the detailed content of How to achieve non-stretching effect of images in css. For more information, please follow other related articles on the PHP Chinese website!