Adding a Background Image in CSS with the background-image Property
With the help of CSS, we can place any background image using the background-image property.
Let’s learn some facts about this awesome and useful property:
- The background-image property can set the background of any element specified in your HTML page.
- Use the background-image property only to place background images, not to place images in your content.
- The reason why the background property exists is to make elements look better.
- Images specified with the background-property are set to a URL. The URL can be a relative path or a website link (http://…).
- By default, images specified with the background-image property are positioned in the top of your browser window.
- By default, images specified with the background-image property are repeated. To fix that, we have a background-repeat property available.
- This property is supported in all main browsers.
Now that you know more about the background-image property let’s learn how to use it:
Create a HTML page, name it “index” and add any element. For example, I added a class for a footer and I included a paragraph tag inside of it.
Visit <a href="http://cssatoms.com/" title="www.cssatoms.com" target="_blank">www.cssatoms.com</a> for more CSS tutorials.</p>
<!-- end .footer --></div>
Next, I would like to improve the attractiveness of the footer class I created by adding a nice image for its background.
Inside the folder where your index.html page was saved, create a New Folder and name it “images”. There we are going to save our background image.
Go ahead and create a New CSS and link it to you HTML page.
Look for any image you would like to set as the background image of your HTML element and save it for web inside the “images” folder.
Preview of my footer-background image:
Now, you just need to specify your image inside your CSS.
Preview in browser:
As you can see, I added the background-image property along with the background-repeat property. Here is an explanation of the properties that I added:
- background-image: the URL was set to a relative path. There we declared where our image is located.
- background-repeat: the repeat-x specification makes our image repeat horizontally. If you prefer to repeat your image vertically choose the repeat-y specification.
- height: I declared the height of my image, so now the height of my div class is set.
- padding properties: It defined the space between the paragraph tag and the div.
- text-align and color properties: they stylized the content inside the footer.
That’s all about the background-image property. Now, you know how to decorate your elements with background images. Have fun!