No Repeat Background Image in HTML
In this article, we will see how to set a no-repeat background image in HTML.
How to create a not-repeating background image
If you set the background image using the CSS background-image property, by default the image will be repeated both horizontally and vertically to cover the entire container, like
HTML
<div id="container">
<p >Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</p>
</div>
CSS
#container{
background-image: url('./star.webp');
width:400px;
height: 400px;
border: 1px solid black;
background-color: red;
}
p{
color: yellow;
padding: 10px;
font-size: 20px;
font-weight: bold;
}
You can set the background image with the background color as in the above example code.
To stop the image from repeating by default, you need to set the CSS background-repeat property to “no-repeat“. Additionally, you need to set the background-size: cover, it is used to make sure the image covers the entire container without distortion. The image will be scaled to the largest size where both its width and height can fit the container, potentially cropping some parts of the image.
#container{
background-image: url('./star.webp');
width:400px;
height: 400px;
border: 1px solid black;
background-color: red;
background-repeat: no-repeat;
background-size: cover;
}
If you want to display high-resolution or large images without compromising their quality by repeating them, you can use no Repeat Background Image. In cases where you want the background image to blend seamlessly with other design elements, avoid repeating seams.
Why we should set ‘no-repeat’?
If you set the CSS background-repeat property to ‘no-repeat’ the background image will not repeat. By default background image will repeat the bg-image for full width and height. If the size of your background image is exactly the container width and height then it won’t repeat and if the size of your background image is smaller than the container width and height it will repeat until it covers the entire element.
So, by setting the ‘background-size : covers’, the size of your background image will automatically cover the element. At that point, you don’t need to use the background-repeat attribute.