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: fillHow 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
- Tumblr
- Telegram
Related
Từ khóa » Html Background Image Stretch To Fit Without Css
-
How To Fit Background Image In Html Without Css?
-
How To Stretch Background Image In Html Without Css?
-
Stretching Images When Using As Background Image - Stack Overflow
-
Html Background Image Full Screen Without Css Code Example
-
How To Stretch A Background Image To Fit A Web Page - ThoughtCo
-
HTML Background Images - W3Schools
-
How To Create A Full Page Image - W3Schools
-
HTML Stretch Background Image
-
HTML How To Make Background Image Fit Screen - YouTube
-
Object-fit - CSS: Cascading Style Sheets - MDN Web Docs - Mozilla
-
How To Scale And Crop Images With CSS Object-fit | DigitalOcean
-
Background-size - CSS-Tricks
-
A Deep Dive Into Object-fit And Background-size In CSS
-
How To Resize An Image In HTML?