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 |
---|---|
|
|
|
|
|
|
|
|
In this example, we present different ways to stretch background image to element size, depending on the effect you want to achieve.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
div {
7
margin: 3px;
8
border: 1px solid black;
9
background-image: url("https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png");
10
}
11
12
.stretch {
13
background-size: 100% 100%; /* background-size: width height */;
14
}
15
16
.cover { background-size: cover; }
17
18
.contain { background-size: contain; }
19
20
.contain-norepeat {
21
background-size: contain;
22
background-repeat: no-repeat;
23
}
24
25
</style>
26
</head>
27
<body>
28
<p>stretch - height and width = 100%:</p>
29
<div class="stretch" style="width: 150px; height: 100px;"></div>
30
<div class="stretch" style="width: 100px; height: 150px;"></div>
31
<p>cover:</p>
32
<div class="cover" style="width: 150px; height: 100px;"></div>
33
<div class="cover" style="width: 100px; height: 150px;"></div>
34
<p>contain:</p>
35
<div class="contain" style="width: 150px; height: 100px;"></div>
36
<div class="contain" style="width: 100px; height: 150px;"></div>
37
<p>contain with no-repeat:</p>
38
<div class="contain-norepeat" style="width: 150px; height: 100px;"></div>
39
<div class="contain-norepeat" style="width: 100px; height: 150px;"></div>
40
</body>
41
</html>