DhiWise Logo

Design Converter

  • Technologies
  • Resource
  • Pricing

Education

How to Add and Style HTML Background Image: A Beginner's Guide

Last updated on Jun 4, 2024

14 mins read

HTML stands for HyperText Markup Language, and it is the foundational building block of web development. It provides the basic structure of web pages, allowing developers to define the content and layout of a web page. However, to truly enhance the visual appeal of a web page, background images are often employed.

Background images play a crucial role in the design and user experience of a website. They can convey emotions, brand identity, and visual interest, making the web page more engaging for visitors. With the right background image, you can transform the entire look and feel of your web page, making it more appealing and professional.

Understanding HTML and CSS

HTML (HyperText Markup Language) is the skeleton of a web page, providing the essential structure and content. It defines the various HTML elements such as headings, paragraphs, and divs that make up the web pages you interact with daily. HTML elements are the building blocks that hold and display the content on the web page, but on their own, they lack the stylistic flair that makes a web page visually appealing.

CSS (Cascading Style Sheets), on the other hand, is the language that styles these HTML elements. It allows you to add colors, fonts, layouts, and, importantly, background images to your web page. CSS enhances the HTML structure by providing a wide array of stylistic options that can be applied to HTML elements, making your web pages not just functional but also attractive.

Preparing Your Image

Choosing the Right Image

Before you add background images to your web pages, it's essential to select the right image that aligns with your design goals and website's performance requirements. The resolution of your image should be high enough to appear crisp on modern displays, but not so high that it unnecessarily increases the file size. Similarly, the size of the image should be appropriate for its intended use; a background image that covers the entire browser window may need to be larger than one that only covers a portion of the web page.

The format of the image is also crucial. Common web-friendly formats include JPEG, PNG, and WebP. JPEGs are typically used for photographs and images with gradients, PNGs are better for images with transparency or text, and WebP offers high-quality results with smaller file sizes.

Optimizing Images for the Web

Optimization is key to ensuring that your web pages load quickly. Large image files can slow down your website, leading to a poor user experience. To optimize your images, you can use various online tools or software to compress them without losing significant quality. Compression reduces the file size, making the image quicker to load.

When saving images, choose settings that balance quality and file size. For instance, reducing the quality of a JPEG might slightly degrade the image but can significantly reduce the file size. Also, consider using responsive images that adjust to different screen sizes and resolutions, ensuring that you're not serving larger images than necessary for the viewing device.

Adding a background with <picture> Element

The <picture> element in HTML is a container used to specify multiple <source> elements, each containing different versions of an image to display. The browser will choose the most appropriate source based on the current viewport size, pixel density, and other factors.

The <picture> element does not directly set a background image; instead, it is used for content images. However, it can be used creatively with CSS to simulate background image behavior while providing the benefits of responsive image selection.

Here's an example of how the <picture> element can be used to serve different images based on the screen width:

1<picture> 2 <source media="(min-width: 1200px)" srcset="large-image.jpg"> 3 <source media="(min-width: 768px)" srcset="medium-image.jpg"> 4 <source media="(min-width: 480px)" srcset="small-image.jpg"> 5 <img src="default-image.jpg" alt="Descriptive text for the image"> 6</picture>

In this example, the browser will display large-image.jpg on screens that are at least 1200 pixels wide, medium-image.jpg on screens that are at least 768 pixels wide, and small-image.jpg on screens that are at least 480 pixels wide. If none of the media conditions are met, or if the browser does not support the <picture> element, the <img> element's src attribute will be used, and default-image.jpg will be displayed.

Adding a Background Image with Inline CSS

Inline CSS involves adding styles directly to an HTML element using the style attribute. This attribute can include any CSS property, including those that set background images. While inline styles are quick to implement, they are generally not recommended for large-scale use because they mix content with presentation and can make later maintenance more challenging.

Syntax for Inline CSS Background Image

To apply a background image using inline CSS, you would include the background image property within the style attribute of the relevant HTML tag. Here's the syntax for adding a background image to the body element using inline CSS:

1<body style="background-image: url('image-url.jpg');"> 2 <!-- Content goes here --> 3</body>

In this example, the background image URL is the path to your image file, which will be displayed as the background of the body element. The background image is applied directly to the opening tag of the body element using the style attribute.

Example of Inline CSS Background Image Code

Here's a complete example of how to add a background image to the entire page using inline CSS:

1<!DOCTYPE html> 2<html> 3<head> 4 <title>Background Image Example</title> 5</head> 6<body style="background-image: url('image-url.jpg'); background-repeat: no-repeat; background-size: cover;"> 7 <h1>Welcome to My Website</h1> 8 <p>This is an example of adding a background image using inline CSS.</p> 9</body> 10</html>

Example of Inline CSS Background Image Code

In the above example, the background image URL points to an image hosted on a server. The background-repeat property is set to no-repeat to prevent the image from tiling, and the background-size property is set to cover to ensure that the image covers the entire browser window, adjusting to the size of the window while maintaining its aspect ratio.

Adding a Background Image with Internal CSS

Explanation of the ‘<style>’ Tag

Internal CSS is defined within the <head> section of an HTML document using the <style> tag. This method is a step towards separating content (HTML) from presentation (CSS), making it easier to manage styles for a single page. The <style> tag contains CSS rules that apply to elements within the HTML document.

CSS Syntax for Background Images

When using internal CSS, you can define various properties related to background images. Here are the key properties:

  • background-image: Sets the image to be used as the background.

  • background-repeat: Defines whether the background image should repeat (tile) and how it should do so.

  • background-position: Specifies the starting position of the background image.

  • background-size: Determines the size of the background image, allowing it to be stretched or scaled to fit the container.

Example of Internal CSS for a Background Image

Below is an example of how to use internal CSS within the <style> tag to add a background image to the body element of a web page:

1<!DOCTYPE html> 2<html> 3<head> 4 <title>Internal CSS Background Image Example</title> 5 <style> 6 body { 7 background-image: url('image-url.jpg'); 8 background-repeat: no-repeat; 9 background-position: center center; 10 background-size: cover; 11 } 12 </style> 13</head> 14<body> 15 <h1>Welcome to My Website</h1> 16 <p>This is an example of adding a background image with internal CSS.</p> 17</body> 18</html>

Example of Internal CSS for a Background Image

In this example, the background image is set to cover the entire body element, without repeating, and is centered both horizontally and vertically. The background-size property is set to cover to ensure the image covers the entire element, adjusting to the size of the window while maintaining its aspect ratio. This approach provides a clean and maintainable way to style your web page with a background image.

Adding a Background Image with External CSS

External CSS files offer several advantages over inline and internal styles. By separating the CSS into its own file, you create a clear distinction between content and presentation, which leads to better organization and maintainability. This separation allows you to apply the same styles across multiple web pages by linking to a single CSS file, making it easier to update and manage styles site-wide. Additionally, because the browser caches external CSS files, this can lead to faster loading times for users as they navigate through different pages of your website.

To use an external stylesheet, you must link it to your HTML document using the <link> tag within the <head> section. The <link> tag has several attributes, but the most important ones for linking a stylesheet are rel, which should be set to "stylesheet", and href, which specifies the path to the CSS file.

Here's how to link an external CSS file:

1<head> 2 <link rel="stylesheet" href="styles.css"> 3</head>

In this example, styles.css is the name of the external stylesheet that contains your CSS rules.

Writing the CSS Code for Background Images in an External Stylesheet

In your external CSS file, you would write the CSS rules just as you would in an internal stylesheet. Here's how you might define the CSS for a background image:

1/* In styles.css */ 2body { 3 background-image: url('image-url.jpg'); 4 background-repeat: no-repeat; 5 background-position: center center; 6 background-size: cover; 7}

This CSS code sets the background image for the body element, ensuring that it does not repeat and is centered and scaled to cover the entire viewport.

Example of External CSS for a Background Image

Now, let's put it all together. You have your HTML file and your external CSS file (styles.css). Here's what they might look like:

index.html:

1<!DOCTYPE html> 2<html> 3<head> 4 <title>External CSS Background Image Example</title> 5 <link rel="stylesheet" href="styles.css"> 6</head> 7<body> 8 <h1>Welcome to My Website</h1> 9 <p>This is an example of adding a background image with external CSS.</p> 10</body> 11</html>

styles.css:

1body { 2 background-image: url('image-url.jpg'); 3 background-repeat: no-repeat; 4 background-position: center center; 5 background-size: cover; 6}

Example of External CSS for a Background Image

In this setup, the HTML file links to the external CSS file, which contains the styles for the background image. This approach keeps your HTML clean and your styles organized, making it easier to manage the look and feel of your web pages.

Advanced Background Image Techniques

Using Multiple Background Images

CSS allows you to layer multiple background images on a single element by providing a comma-separated list of image URLs in the background-image property. The first image in the list will be the topmost layer, with subsequent images layered behind it.

Here's an example of using two background images on the body element:

1body { 2 background-image: url('top-image.png'), url('bottom-image.jpg'); 3 background-repeat: no-repeat, repeat; 4 background-position: left top, right bottom; 5 background-size: 100px 100px, cover; 6}

Using Multiple Background Images

In this CSS code, the top-image.png is placed at the top-left corner and has a fixed size, while the bottom-image.jpg covers the entire element and repeats if necessary.

Gradient Overlays on Background Images

You can create a gradient overlay on a background image by combining a CSS gradient with an image URL. Gradients are defined using the linear-gradient or radial-gradient functions and can be layered with images to create a visually striking effect.

Here's how to apply a linear gradient overlay on a background image:

1body { 2 background-image: linear-gradient(to bottom, rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url('background.jpg'); 3 background-repeat: no-repeat; 4 background-size: cover; 5}

Gradient Overlays on Background Images The gradient uses RGBA color values with alpha transparency to allow the background image to show through.

Fixed and Scrolling Background Images

The background-attachment property determines whether a background image is fixed with regard to the viewport (fixed) or scrolls with the content (scroll).

Here's how to set a fixed background image:

1body { 2 background-image: url('background.jpg'); 3 background-repeat: no-repeat; 4 background-size: cover; 5 background-attachment: fixed; 6}

FixedandScrollingBackgroundImages

With background-attachment: fixed, the background image will stay in place even as the user scrolls through the page.

Responsive Background Images for Different Screen Sizes

To ensure that background images look good on devices with different screen sizes, you can use media queries to apply different background properties depending on the screen size.

Here's an example of using media queries for responsive background images:

1body { 2 background-image: url('background.jpg'); 3 background-repeat: no-repeat; 4 background-size: cover; 5} 6 7@media (max-width: 768px) { 8 body { 9 background-image: url('background-mobile.jpg'); 10 } 11}

In this example, background.jpg is used for screens wider than 768 pixels, while background-mobile.jpg is used for screens 768 pixels or narrower.

Common Issues and Troubleshooting

Image Not Displaying

One of the most frequent issues when working with background images is that the image fails to display. This can be due to several reasons:

  • Path Issues: The background image URL must point to the correct location of the image file. If the file path is incorrect, the browser will not be able to find and display the image. Ensure that the path matches the actual location of the image in your directory structure or on the web.

  • Typos: A simple typo in the file path or image name can prevent the image from displaying. Double-check the spelling and case sensitivity of your file names and paths.

  • File Permissions: On a server, incorrect file permissions can prevent images from being displayed. The image file must be readable by the web server for it to be served to users.

Background Image Not Covering the Entire Element

If your background image is not covering the entire element, the issue might be with the background-size property. To ensure that the image covers the entire element, you can use the cover value:

1element { 2 background-image: url('image-url.jpg'); 3 background-size: cover; 4}

This will scale the background image to be as large as possible so that the entire element is covered.

Image Repeating When It Shouldn’t

The default behavior of the background-repeat property is to tile the background image across the entire element. If you do not want the image to repeat, you need to explicitly set the property to no-repeat:

1element { 2 background-image: url('image-url.jpg'); 3 background-repeat: no-repeat; 4}

This will ensure that the image is displayed only once and not repeated.

Slow Loading Times Due to Large Image Files

Large image files can significantly slow down your web page loading times. To address this:

  • Optimize Images: Use image compression tools to reduce file size without sacrificing too much quality. Choose the correct format for your images (JPEG, PNG, WebP) based on the needs of your design.

  • Use Appropriate Dimensions: Scale your images to the largest size they will be displayed on your web page. There's no need to use an image that's larger than the maximum viewable size.

  • Consider Lazy Loading: If your web page has multiple images, consider implementing lazy loading, which loads images only as they are about to enter the viewport.

Performance Considerations

The performance of your web pages can be greatly affected by how you handle background images:

  • Loading Times: Optimize your images to reduce their file size without compromising quality. This will help your web pages load faster.

  • Image CDN: Consider using an Image Content Delivery Network (CDN) to serve your images. CDNs can significantly improve load times by hosting your images on multiple servers around the world, reducing the distance between the server and the user.

  • Responsive Images: Use media queries to serve different image sizes for different devices. This prevents mobile devices from downloading unnecessarily large images intended for desktop viewing.

  • Caching: Ensure that your web server is configured to cache images properly. This means that returning visitors will not need to re-download images they have already seen, which can speed up the loading of your web pages.

Conclusion

Incorporating background images into your HTML can significantly enhance the visual appeal of your web pages. Throughout this blog post, we've explored various methods to add background images, from inline and internal CSS to external stylesheets, and delved into advanced techniques for creating responsive and engaging designs. We've also addressed common issues and troubleshooting tips to ensure your images display correctly and maintain site performance.

With these best practices, you can create beautiful, functional, and efficient web pages that stand out in the digital landscape. Happy coding!

Short on time? Speed things up with DhiWise!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Read More