HTML How to set a background image? – CSS background-image

  • Reading time:7 mins read

HTML How to set a background image? – syntax

 

<style>
div {
  background-image: url('img_girl.jpg');
}
</style>

To what can you add a background image in HTML, and how?

You can set a background image for almost any HTML element, whether it’s a section of a page <div>, a paragraph <p>, or the whole page <body>.

To add a background image to an HTML element, you use the style attribute, select the element you want to add a background to with the appropriate CSS selector and specify the path to the background image in the background-image property.

 

HTML How to set a background image

 

Background image for the whole page – HTML background image

If you want to set a background image for the whole page, you have to define it in the <body> element. 

Repetition of the background image

If the background image is smaller than the element to which it is added, the image will repeat, both horizontally and vertically, until it reaches the edges of that element.

This is how the background image is displayed by default:

 

 

HTML How to set a background image? – Background image, no repetition

To avoid repeating the background image, the background-repeat property should be set to no-repeat.

 

 

HTML How to set a background image? – Full-page background image

 

If you want the background image to be exactly the same size as the element you’re setting it behind, use the cover property for background-size.

Be careful, this can distort the proportions, stretching the image to fill the element or page. If you want to avoid this, set the background-attachment to fixed, so that the original aspect ratios are preserved.

 

You can also set the image to fill the page even if you resize the browser window. To do this, set the background-size to 100% 100%. This way the background image will follow the scaling of the browser window.

Summary

In summary, from the examples so far, you can see that to set the background image, you need to use the appropriate CSS properties on the selected HTML element.

If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of video tutorials in English.

In our Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.

HTML and CSS:

JavaScript:

Java:

Other materials:

Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING

Not sure if programming is for you? With CodeBerry you’ll like it.