How to Make a Background Image Not Repeat
To make a background image not repeat in HTML, specify no-repeat
in the background-repeat
property or the background
shorthand property.
The above example uses the background-repeat
property to set the image to no-repeat
. This prevents the image from repeating across the full width and height of the element.
The original image looks like this:
So by using no-repeat
, we are simply making the background image appear as it is, without repeating.
Repeat Horizontally
You can also prevent an image from repeating vetically, while allowing it to repeat horizontally (and vice versa).
To make a background image repeat horizontally, use background-repeat: repeat-x
Repeat Vertically
You can make a background image repeat vertically by using background-repeat: repeat-y
The background
Shorthand Property
The background
property is a shorthand property that allows you to set multiple properties at once. You can use it to set both your image location and its repeating property in one place.
Using the background
shorthand property will allow you to add other background properties, such as color, background size, position, and more.
Use background-position
to specify the position your background image appears within its container and/or background-size
to specify how large the background should appear. These can also be specified in the background
shorthand property.
Putting Styles into an External Style Sheet
The above example uses inline styles but could just as easily have used an external style sheet or an embedded style sheet (styles embedded in the document head).
If you place the code into an external style sheet, here's a snippet of what that might look like:
(Note that I use background-repeat
on one line and background
on the other — both will acheive the same result).
Here's a snippet of what the HTML code could look like:
Adding the above external style sheet will set a background image against the <body>
element. It won't repeat because I've specified no-repeat
.
This example also sets a background image against a class that I called .myBox
. Now, any HTML element that uses that class will have the background image applied to it. It will repeat horizontally because I specified repeat-x
.
Why Set 'no-repeat'?
Setting 'no-repeat' is optional. The default behavior of a background image is to repeat across the full width and height of the element that it's applied to. Of course, you'll only see this effect if the background image is smaller than its container. It will repeat as many times as necessary until it covers the whole element. If the image is the same size or larger than its container there will be no need to repeat (and of course, no way to repeat) as it already covers the whole container.
The background-repeat
property gives you control over how your image repeats.