Fit Image To Div Without Stretching | CSS Background-size Property
Có thể bạn quan tâm
You want to Fit the image to div and want to set it a specific width and height (in pixels) on the HTML web page. But the problem is to Fill div with an image without stretching it.
If you set width and height using CSS (width:250px; height:300px), the image will be stretched, and It may be ugly.
Let’s see the images and Fit image to div
Original Image: 1080 x 1920

Stretched Image: width: 250px; height: 300px;

Filled Image: width: 250px; height: 300px;
object-fit: fill
How to fit image without stretching and maintain aspect ratio?
Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property.
- contain will give you a scaled-down image.
- cover will give you a scaled-up image
Example:
<!DOCTYPE html> <html> <style type="text/css"> .container { width: 250px; height: 300px; background-image: url(ca.jpg); background-size: contain; background-repeat: no-repeat; background-position: 50% 50%; } </style> <body> <div class="container"></div> </body> </html>Output:

Q: How do you stretch an image to fill a <div> while keeping the image’s aspect-ratio?
Answer: Use background-size: contain, the image is resized to fit the height but the width isn’t entirely filled.
OR
You could just state the width of the image and have the height auto
.div img { width: 310px; height: auto; } <div class="div"> <img src="#" title="#"> </div>Do comment if you have any doubts and suggestions on this tutorial.
Note: The All Examples code HTML Fit image to div is tested on the Safari browser (Version 12.0.2).OS: macOS 10.14 CatalinaCode: HTML 5 Version
Share this:
- More
- X
- Tumblr
- Telegram
Related
Từ khóa » Html Image Stretched
-
How To Resize An Image In HTML?
-
Html - How Do You Stretch An Image To Fill A
While Keeping The ...Stretched Image Problem - CSS-Tricks
CSS Object-fit Property - W3Schools
HTML Stretch Background Image
How To Stretch And Scale An Image In The Background With CSS
How To Stretch A Background Image To Fit A Web Page - ThoughtCo
Stretch Background Image
CSS Image Size, How To Fill, Avoid Stretch On Image Css - YouTube
How To Prevent Image Stretching With Flexbox - Techstacker
Why Are My Images Stretched Website Design? - Systran
Stretch Image Html Code Example
The CSS Way: 3 Tricks To Resolve Image Stretching Issues In Your ...
Resizing Background Images With Background-size - CSS
Copyright © 2022 | Thiết Kế Truyền Hình Cáp Sông Thu