Add Background Images in HTML using CSS

Learn how to add background images to HTML elements using CSS. This tutorial covers adding background images to divs, full-page backgrounds, controlling repetition, and using `background-size` for cover and stretch effects.



Adding Background Images in HTML

You can easily add background images to HTML elements using CSS. This enhances the visual appeal of your web pages.

Adding Background Images to Elements

Use the CSS background-image property within the HTML style attribute to set a background image for an element.

Example: Background Image on a Div

<div style="background-image: url('image.jpg'); width:300px; height:200px;"></div>

Replace 'image.jpg' with the actual path to your image file.

You can also define styles in a separate CSS file and link it to your HTML.

Full Page Background Image

To apply a background image to the entire page, target the <body> element:

Example: Full Page Background

<body style="background-image: url('page_background.jpg');">
  <!-- Your page content -->
</body>

Background Repeat

By default, background images repeat horizontally and vertically. To prevent repetition, use background-repeat: no-repeat;.

Example: No-Repeat Background

background-repeat: no-repeat;

Background Cover

To make the background image cover the entire element without stretching or distortion, use background-size: cover; and background-attachment: fixed; (to keep the image fixed even when scrolling).

Example: Background Cover

background-size: cover;
background-attachment: fixed;

Background Stretch

To stretch the background image to fit the entire element, even if it distorts the image, use background-size: 100% 100%;

Example: Background Stretch

background-size: 100% 100%;

Learn More About CSS Backgrounds

For a deeper dive into CSS background properties and options, explore our comprehensive CSS Background tutorial:

CSS Background Tutorial