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 Div
-
How To Stretch The Background Image To Fill A Div - Stack Overflow
-
How To Stretch A Background Image To Fit A Web Page - ThoughtCo
-
CSS Background-size Property - W3Schools
-
Resizing Background Images With Background-size - CSS
-
Perfect Full Page Background Image - CSS-Tricks
-
Background-size - CSS-Tricks
-
How To Stretch And Scale An Image In The Background With CSS
-
How To Auto-resize An Image To Fit Into A DIV Container Using CSS
-
How To Stretch A Background Image In CSS
-
Background Image Fit To Div Code Example - Code Grepper
-
How To Auto-resize An Image To Fit A Div Container Using CSS?
-
Css Background Image Size To Fit Div - Add Multiple ... - Pakainfo
-
How To Resize An Image In HTML?
-
How To Set Size Of Background Image Fit To The Div