background-repeat
Definition
In CSS, the background-repeat
property specifies how a background image should be repeated within an element.
Examples
To repeat a background image both horizontally and vertically:
body {
background-image: url(image.jpg);
background-repeat: repeat;
}
To repeat a background image horizontally only:
body {
background-image: url(image.jpg);
background-repeat: repeat-x;
}
To repeat a background image vertically only:
body {
background-image: url(image.jpg);
background-repeat: repeat-y;
}
To display a background image only once, without repeating:
body {
background-image: url(image.jpg);
background-repeat: no-repeat;
}
To display a different image on the left and right sides of an element:
body {
background-image: url(image-left.jpg), url(image-right.jpg);
background-repeat: no-repeat, no-repeat;
background-position: left, right;
}
To repeat a background image along the diagonal of an element:
body {
background-image: url(image.jpg);
background-repeat: repeat;
background-position: top left, bottom right;
background-size: 50% 50%;
}
Values
Value | Description |
---|---|
url(URL) | Specifies the URL of an image to use as the background. |
none | No background image will be displayed. This is the default value. |
initial | Sets the property to its default value. |
inherit | Inherits the property from the parent element. |
-webkit-gradient | Specifies a gradient as the background image. (Only works in webkit browsers) |
Best Practices
- Use relative URLs for your background images, especially if you are using a content management system (CMS) or version control system (VCS). This makes it easier to move your website or web application to a different domain or server.
- Optimize your background images for the web by compressing them and using the appropriate file format. This will help reduce the page load time and improve the user experience.
- Use responsive design techniques to ensure that your background images look good on different devices and screen sizes. This may involve using the background-size and background-position properties to scale and position the image appropriately.
- Consider the performance impact of using large or high-resolution background images. These images can significantly increase the page load time and use more bandwidth, which can be a problem for users on slow internet connections.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |
However, some older web browsers may not support the background-image property, or they may only support a limited set of values. For example, the -webkit-gradient value is only supported by webkit-based browsers such as Google Chrome and Safari.