EN
CSS - stretch background image to element size
0
points
In this article, we would like to show you how to stretch background image to element size with CSS.
Preview | Style |
---|---|
|
|
|
|
|
|
|
|
Practical example
In this example, we present different ways to stretch background image to element size, depending on the effect you want to achieve.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
div {
margin: 3px;
border: 1px solid black;
background-image: url("https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png");
}
.stretch {
background-size: 100% 100%; /* background-size: width height */;
}
.cover { background-size: cover; }
.contain { background-size: contain; }
.contain-norepeat {
background-size: contain;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<p>stretch - height and width = 100%:</p>
<div class="stretch" style="width: 150px; height: 100px;"></div>
<div class="stretch" style="width: 100px; height: 150px;"></div>
<p>cover:</p>
<div class="cover" style="width: 150px; height: 100px;"></div>
<div class="cover" style="width: 100px; height: 150px;"></div>
<p>contain:</p>
<div class="contain" style="width: 150px; height: 100px;"></div>
<div class="contain" style="width: 100px; height: 150px;"></div>
<p>contain with no-repeat:</p>
<div class="contain-norepeat" style="width: 150px; height: 100px;"></div>
<div class="contain-norepeat" style="width: 100px; height: 150px;"></div>
</body>
</html>