CSS image fills div
CSS https://coder-cafe.com/wp-content/uploads/2025/09/images fill the div
In web development, sometimes we want to completely fill an element with an image. Typically, the simplest way to achieve this is using the CSS background-size
property. This article will detail how to use CSS to make an image fill a Div element.
CSS background-size
Property
In CSS, the background-size
property can be used to control the size of background https://coder-cafe.com/wp-content/uploads/2025/09/images. This property can accept different values:
auto
: Keep the image at its original size.cover
: Keep the image’s aspect ratio intact and fill the entire element; it may be cropped.contain
: Keep the image’s aspect ratio intact and fully enclose it within the element.
Make the image fill the div.
First, we need an HTML structure to display the div and image:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Full Background Image</title>
<link rel="stylesheet" css">
</head>
<body>
<div class="container">
<div class="image"></div>
</div>
</body>
</html>
Next, we need some CSS styles to define the styles of the div and image:
body {
margin: 0;
padding: 0;
}
.container {
width: 100vw; /* Set the div width to the screen width */
height: 100vh; /* Set the div height to the screen height */
}
.image {
width: 100%;
height: 100%;
background-image: url('https://coder-cafe.com/wp-content/uploads/2025/09/image.jpg'); /* Set the background image path */
background-size: cover; /* Make the image fill the entire div */
background-repeat: no-repeat; /* Prevent image repeating */
background-position: center; /* Set the image position within the div */
}
In the above code, we set a width of 100vw and a height of 100vh for .container
to make the div fill the entire screen. Then, we set the background image path in .image
and use background-size: cover;
to make the image fill the entire div.
Running Results
When we open this HTML file in a browser, we see an image that fills the entire screen.
Through the above code, we’ve successfully achieved the effect of making an image completely fill a div element. This method is simple and practical, and it’s a common requirement in web development. We hope this article can help you solve similar problems.