EN
CSS - fill / cover with image all div keeping image ratio
6
points
In this article we are going to show how in CSS fill with image all div to cover all available space keeping image ratio.
Note: for JavaScript version with
imgelement read this article.
CSS styling example
In this section we cover all available div space with image keeping the image ratio.
Useful style property for filling is background-size: cover;
Note: it is important to set size for
divelement.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#image1 {
border: 1px solid red;
background-repeat: no-repeat;
background-size: cover; /* <-------------- required */
background-position: 50%; /* <------------ required */
background-image: url('https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png'); /* <--- required */
width: 120px; /* <------------------------ required */
height: 200px; /* <----------------------- required */
}
#image2 {
border: 1px solid red;
background-repeat: no-repeat;
background-size: cover; /* <-------------- required */
background-position: 50%; /* <------------ required */
background-image: url('https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png'); /* <--- required */
width: 300px; /* <------------------------ required */
height: 120px; /* <----------------------- required */
}
</style>
</head>
<body>
<div id="image1"></div>
<br />
<div id="image2"></div>
</body>
</html>
Used resource:
