How to Add Background Image in HTML: A Simple Step-by-Step Guide!
Updated on Sep 16, 2025 | 17 min read | 71.25K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Sep 16, 2025 | 17 min read | 71.25K+ views
Share:
Table of Contents
Did you know? Over 52% of professional developers rely on HTML/CSS, making it an essential skill for every web developer in 2025! |
Want to know how to add background image in HTML using CSS? This simple technique can instantly make your website more engaging and visually appealing. A background image helps set the mood of your site, improves user experience, and supports branding. For instance, a travel blog might use a scenic photo to spark a sense of adventure the moment someone lands on the page.
In this guide, you’ll learn step by step how to add background images using both HTML and CSS. By the end, you’ll be able to create clean, professional, and attractive backgrounds that match your website’s purpose.
Explore our range of Software Engineering Course and start building the expertise in HTML, CSS, and more needed to create stunning websites and webpages!
HTML is a powerful coding language for creating websites. It is combined with CSS while designing and constructing websites. Therefore, it should go without saying that learning HTML is a necessary first step if you want to succeed in the field of Web development. Now let’s answer the question how to add background image in html.
The background image attribute found inside the <body> tag is the most popular and straightforward method of adding a background image. We can add HTML background image to be displayed on a web page using the various methods:
If you’re looking to enhance your expertise in HTML and build visually compelling websites, here are some top-rated courses to help you get started:
Here's a table with a brief description of each method, so you can easily understand when to choose each one:
Method | Description | When to Use |
Using the Background attribute (using HTML tag) | This method uses the background attribute directly within an HTML tag (like <body> or <div>). It's a simple, outdated method. | Use for quick, small-scale applications or simple demos. Not recommended for complex websites. |
Using an Internal Style Sheet (CSS) | Involves placing CSS rules within a <style> tag in the <head> section of your HTML. You can target specific elements. | Ideal for single-page sites or small projects where styles are limited to that page. |
Without Using CSS | Simply using the background attribute in an inline style for specific HTML elements (no separate CSS file). | Quick and simple for small, one-time style changes, though not efficient for larger projects. |
Using Notepad (with external CSS) | Writing HTML and CSS in separate files (HTML in Notepad, CSS in another file), then linking the two using a <link> tag. | Best for larger projects, as it separates structure (HTML) from presentation (CSS) for maintainability. |
Now let’s explore these 4 methods to add background image in HTML in detail:
Software Development Courses to upskill
Explore Software Development Courses for Career Progression
This is one of the oldest methods to add a background image in HTML, used directly within the <body> tag. Although it's now considered outdated and not supported in HTML5, it still appears in legacy code.
Let’s start with setting up your files:
Step 1: Create a folder to hold your HTML file and background
Make a folder on your computer with a name you can recall later.
Although the folder name is completely up to you, it's best to get into the habit of giving your files and folders recognizable, short, single-word names when working with HTML.
Also Read: Structure of HTML: The Essential Guide to Building Web Pages in 2025
Step 2: Put the background image into the HTML folder
Put the background image in the HTML folder if you want to use it.
Use a higher-resolution image as your background if you aren't too concerned about making sure your website will function well on older devices with slower internet connections. To make any text on top of the background image easier to read, choose a simple image with subtle, repetitive patterns.
Step 3: Open a text editor or HTML editor
Simple text editors like NotePad on Windows or TextEdit on Mac can be used to create HTML files. Another option is to use a WYSIWYG (what-you-see-is-what-you-get) HTML editor like Adobe Dreamweaver.
At the top of the page, if you're using a WYSIWYG editor, select the option to open a new HTML file.
Also Read: Difference Between HTML and HTML 5 : Features and Advantages
Step 4: Click File It’s in the menu bar at the top of the page
Step 5: Click Save as (Notepad) or Save (TextEdit)
It's listed below in the file menu. On a computer, select Save As from the "File" drop-down menu. On a Mac, select Save from the drop-down menu.
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Step 6: Type a name for the HTML document
The first page of a website is typically referred to as the "index," but you can name the page whatever you like. In the text box next to "File Name," enter the file's name.
Also Read: How to Become a Full Stack Developer in 2025? 8 Steps, Skills, and Careers
Step 7: Change the file type to an HTML document
If you're working in a WYSIWYG editor, all you have to do is save the document. Use the steps below to save the document in HTML format if you're creating HTML in NotePad or TextEdit.
Step 8: Click Save
The “save” option is located in the window's lower-right corner. This saves the text file as an HTML file.
The next stage is writing the HTML file. Here’s how you can do that:
Step 1: Type <! DOCTYPE html > at the top of the HTML document
Open and closed tags make up HTML code. Every properly written HTML page should begin with <!DOCTYPE html>. This indicates to a web browser that the file is an HTML file.
Step 2: Write <html> in the next line
This is the first tag in your HTML code. This instructs the browser that your HTML code begins here.
Step 3: Type <head> in the next line
This is the first tag in the HTML document's Head section. The head contains meta information that the web browser does not display. This section contains information such as the page title, as well as Cascading Style Sheets (CSS) that format the look of the HTML code.
Step 4: Type <title> Page Title </title>
This is the HTML code that contains your web page's title. The "<title>" tag is the first tag in the HTML code for the Page title. The closing tag is "</title>" of the tag. Replace "Page Title" with whatever title you want to give your HTML page. This text will appear at the top of the web browser in the browser tab.
Step 5: Type </head> in the next line
This is the tag that ends your HTML document's head. If you want to add any additional information or style sheets to your HTML document, place them after the "<head>" opening tag and before the "</head>" closing tag.
Step 6: Type <body> in the next line
This is the opening tag for your HTML document's body. The body contains all of your website's visual elements. This includes text, images, buttons, and other visible web page elements.
Step 7: Type <div style=“background-image : url ( ‘ [ image url ] ‘ ); “ > in the next line
This is the HTML tag for including a background image on your website. Replace "[image url]" with the actual URL of the image to be added. This can be the online server location of an image or the local location of an image on your computer.
You can also use CSS to set a background image.
When you use a filename that does not include a file path or URL (for example, background-image: url("background.png");), the web browser will look for the named image in the web page folder, if the file is in a different folder on your file system, you must include the full path to that file.
Step 8: Finish the rest of your HTML document
If you want to include other HTML elements on your web page, such as text, images, videos, links, buttons, and so on, make sure to put them in the "Body" section of your HTML document.
Step 9: Type < / body > in the last line
This is the tag that wraps your HTML document's body. When you've finished adding all of the HTML elements you want to include in your document, add this tag at the end.
Step 10: Type < / html > at the very end
This is the tag used to wrap your HTML document. Put this tag on the last line.
Step 11: Save the HTML file
When you are finished, click File and then Save to save your work. Your entire HTML document should resemble this:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div style="background-image: url('https://www.website.com/images/image_background.jpg');">
</body>
</html>
Also Read: Top 25+ HTML Project Ideas for Beginners [Source Code]
This method involves writing CSS rules within a <style> tag in the <head> section of your HTML file. It allows you to add a background image to specific elements (like body, div, etc.) and customize properties such as size, repeat, and position.
Note: Modern JavaScript frameworks, such as React.js and Vue.js, often handle background images using inline styles or scoped CSS. For example, in React, you can set a background image directly on a div using a style object:
<div style={{ backgroundImage: `url('/path-to-image.jpg')`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat' }}>
{/* Content here */}
</div>
This approach helps keep styles scoped and dynamic without relying solely on traditional CSS files.
Follow these steps if you want to know how to add background image in HTML using CSS:
Step 1: Create an HTML document
To create an HTML document, follow the procedures described in Part 2. An open and closing HTML tag, an open and closing head tag, and an open and closing body tag should all be present in your HTML document.
To add a background image, you do not need to use the HTML tag. This section demonstrates how to set a background image using CSS rather than HTML.
Also Read: 15 Amazing CSS Project Ideas Every Beginner Must Try in 2025!
Step 2: Type < style > in the head of the HTML document
The first tag in cascading style sheets is this one (CSS). Before the "</head>" tag and following the "<head>" tag.
You can also create your CSS in a separate CSS document and link it to your HTML document as an alternative.
Step 3: Type body { in the next line
The CSS code that will style the body of your HTML document begins here.
Step 4: Type background-image: url (‘ [ image url ] ‘ ); in the next line
The background image to be used is specified in this line. The actual URL of the image you want to use should be substituted for the text "[image url]".
A filename without a file path or URL, such as background-image: url("background.png");, causes the web browser to search for the named image in the web page folder. You must include the complete path to the file if it is located in another folder on your file system.
Step 5: Type background-repeat: no-repeat; in the next line
By using this line, the web browser is instructed to only show the image once rather than repeatedly.
Step 6: Type background-size: cover; in the next line
This line instructs the web browser to use the image as the background for the entire page.
Step 7: Type} at the end of the “Body “section of your HTML
Make sure to include any additional CSS lines that have an impact on the HTML document's Body at this time. To close the "Body" section of your CSS, enter the symbol "}" in the final line.
Step 8: Type < / style > at the end of your CSS
Write "</style>" at the end once you have included all the CSS you want to. Your CSS is closed by this tag.
Step 9: Save the HTML file
When you are done, click File, followed by Save, to save your work.
Your entire HTML file should resemble the following:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
body {
background-image: url("https://www.website.com/images/image_background.jpg");
background-repeat:no-repeat;
background-size:cover;
}
</style>
</head>
<body>
</body>
</html>
Explanation:
Also Read: Font Family in CSS
The steps listed below must be followed if we want to add a background image using the Background attribute in an HTML document. We can quickly view an image on a web page by following these steps:
Step 1: To begin, enter the HTML code into a text editor of your choice or open an existing HTML file to insert the background attribute.
<!Doctype Html>
<Html>
<Head>
<Title>
Add the Background image using the background attribute
</Title>
</Head>
<Body>
upGrad <br>
Html Tutorial <br>
This page helps us to understand how to show the background image of a web page. <br>
<br>
And this section helps you to understand how to add a background image in Html page using the background attribute.
</Body>
</Html>
Step 2: Place the cursor inside our HTML document's opening <body> tag. After that, type the background attribute as it appears in the block below:
<Body background=" ">
Also Read: How to Become a Successful Web Designer: Key Skills, Expert Tips, and Career Insights
Step 3: The image path for the one we want to add must then be provided. Therefore, enter the image's path in the background attribute. Type the following path if our image is located in the same directory as the HTML file:
<Body background="filename.extension">
<Body background="image.jpg"> <br>
If our image is located in another directory, be sure to enter its correct path so that the browser can easily read it, as explained in the block below.
<Body background="/home/ishan/Desktop/images/image.jpg">
If our image is available online, we can also add it using the URL provided in the block below.
<Body background="https://images.unsplash.com/photo-1540270776932-e72e7c2d11cd?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MTh8fHxlbnwwfHx8fA%3D%3D&w=1000&q=8">
Step 4: In the text editor, we must finally save the HTML file or HTML code.
<!Doctype Html>
<Html>
<Head>
<Title>
Add the Background image using background attribute
</Title>
</Head>
<Body background="https://images.unsplash.com/photo-1540270776932-e72e7c2d11cd?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MTh8fHxlbnwwfHx8fA%3D%3D&w=1000&q=80
">
upGrad <br>
Html Tutorial <br>
This page helps us to understand how to show the background image of a web page. <br>
<br>
And this section helps you to understand how to add the background image in an Html page using the background attribute.
</Body>
</Html>
Output:
upGrad
Html Tutorial
This page helps us to understand how to show the background image of a web page
And, this section helps you to understand how to add the background image in a Html page using the background attribute.
Also Read: 30+ Best HTML Project Ideas and Topics for Beginners and Professionals in 2025
You can easily create a webpage with a background image using Notepad by writing HTML and CSS code manually and saving it with a .html extension. This is a great way for beginners to practice and understand the structure of a web page.
You have to follow these steps
Step 1: Open the Notepad text editor
Use the Windows Start button to search for Notepad. From the Search Results, pick Notepad and click twice. After that, your notepad text editor will launch.
Step 2: Writing HTML Image Syntax
Create an HTML image syntax that requires us to use HTML IMG tags to add and display images inside of our HTML webpage.
<img src="imageFileHere"/>
Step 3: Type the name of your image file
For assigning our image files' names, followed by the image extension, we must use SRC.
<img src="myImage.jpg"/>
Step 4: Save your HTML file
Use the File menu in the Notepad text editor to save your HTML file, or press Ctrl+S to save your HTML file directly in Notepad.
Step 5: Run your HTML file in a browser
Launch the web browser and run your HTML file.
Also Read: Difference Between HTML and JavaScript
Next, let’s look at how you can repeat the background image in HTML.
Repeating a background image can be useful for creating textures or patterns. By default, background images in CSS repeat both horizontally and vertically. However, you can control this behavior using the background-repeat property. Here’s how to do it:
1. Default Repeat
To repeat a background image both horizontally and vertically, you can use the following CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Repeat Background Image</title>
<style>
body {
background-image: url('path/to/your/image.jpg');
background-repeat: repeat; /* Default behavior */
}
</style>
</head>
<body>
<h1>Repeating Background Image Example</h1>
</body>
</html>
2. Horizontal Repeat Only
To repeat the background image only horizontally:
<style>
body {
background-image: url('path/to/your/image.jpg');
background-repeat: repeat-x; /* Repeats the image horizontally */
}
</style>
3. Vertical Repeat Only:
To repeat the background image only vertically:
<style>
body {
background-image: url('path/to/your/image.jpg');
background-repeat: repeat-y; /* Repeats the image vertically */
}
</style>
4. No Repeat
To prevent the background image from repeating:
<style>
body {
background-image: url('path/to/your/image.jpg');
background-repeat: no-repeat; /* Prevents the image from repeating */
}
</style>
Adding and controlling background images using CSS enhances the design of your webpage. Whether using an internal style sheet or managing image repetition, these techniques provide flexibility and ease in creating visually appealing web pages.
Also Read: Difference Between HTML and HTML 5 : Features and Advantages
Next, let’s look at how you can review the HTML file.
Once you've written your HTML code to add a background image, it's important to review the file to ensure everything displays correctly. This step involves opening the .html file in a browser, checking if the background image loads properly, and making sure the layout and text are visible and responsive.
If the image doesn’t show up, double-check the file path, image format, and CSS syntax. Reviewing your HTML file helps catch any errors early and ensures your webpage looks polished and functions as intended.
Step 1: Right-click the HTML document
To the right of it, a pop-up menu is displayed.
Step 2: Select Open with
A list of applications that can open HTML is shown in this.
Step 3: Select the web browser of your choice. You can use any web browser to view the HTML.
Step 4: Review the HTML file
Make sure everything in the file looks correct by going through it one last time.
The HTML file may have been saved as a a.txt or rtf file rather than an HTML document if you see the HTML code when the browser opens instead of the background image. You might want to try using a different text editor to edit the HTML file.
Step 5: Make edits to the HTML file
Place the cursor in the space between the <body> and </body> tags in the text editor window, and then type Hello world!. To see the text on top of the background image, reload the browser window.
Also Read: HTML4 vs. HTML5: Key Differences, Similarities, & Features
Learning how to add background image in HTML is a must for building visually appealing websites. Whether you’re exploring how to add background image in HTML using CSS for more control, or trying out how to add background image in HTML using Notepad as a beginner, the process is simple and effective. With these methods, you can easily design pages that match your style and purpose.
Next, let’s look at how upGrad can help you in learning HTML.
HTML is the cornerstone of web development, allowing you to structure content, integrate multimedia, and design responsive layouts. Mastering image embedding is an essential skill for front-end developers, and this blog’s step-by-step guide equips you with the knowledge to do just that. To take your HTML and web development skills further, upGrad offers beginner-friendly courses that provide hands-on projects and personalized mentorship.
If you're unsure where to begin or which area to focus on, upGrad’s expert career counselors can guide you based on your goals. You can also visit a nearby upGrad offline center to explore course options, get hands-on experience, and speak directly with mentors!
Discover our top-rated Software Engineering courses designed to equip you with the latest industry skills and accelerate your career growth.
Get started with our free software development courses, designed to build your skills and kickstart your journey in tech.
Enhance your software development knowledge with our popular articles, offering insights and tips to boost your expertise and career.
Master the most sought-after software development skills with our expert-led courses, tailored to help you stay ahead in a fast-evolving tech landscape.
Discover the best HTML tutorials and start building strong web development skills from the ground up!
This usually happens because the file path is not pointing to the right location of the image. In HTML, relative paths are based on the location of the HTML file itself, not your project root. For example, if your HTML file is inside a pages/ folder and your image is inside an images/ folder at the same level, the correct path would be ../images/your-image.jpg. The ../ moves one step back in the folder hierarchy. If you get this wrong, the browser won’t be able to find the image. Always double-check spelling, file extensions, and capitalization since browsers treat them as case-sensitive. Also, clear your browser cache, because sometimes an old cached path prevents new changes from showing up.
Yes, you can apply a background image to specific HTML elements like <div>, <section>, or <header> by using CSS. This technique is very useful if you want only certain sections of your website to have unique visuals. For example, you could give your hero banner a background image while keeping the rest of the site simple. You would use CSS like this:
section {
background-image: url('banner.jpg');
background-size: cover;
background-position: center;
}
This makes that section visually stand out. Make sure to test your design on different devices to confirm the background adapts properly, since images may look cropped on smaller screens.
To make a background image responsive, you need to use CSS properties like background-size: cover; and background-position: center;. cover ensures the image always fills the container while maintaining its original aspect ratio. center ensures that important parts of the image are visible and not pushed to the edge. On smaller screens, parts of the image may get cropped, so you may also want to add background-repeat: no-repeat; to avoid repetition. If your image contains critical details like text or logos, use media queries to swap it with a more mobile-friendly version. This way, your background looks good on desktops, tablets, and smartphones without losing quality.
When you place text over a background image, the image can make the text hard to read. This happens because the text doesn’t have enough contrast against the image. A common fix is to add a semi-transparent overlay between the background image and the text. For example:
.overlay {
background: rgba(0,0,0,0.5);
color: white;
padding: 20px;
}
This makes the text more readable while still showing the image behind it. You can also increase padding inside the text container, or apply a solid background color to the text area for full clarity. Good design practices always focus on readability and accessibility, so be sure to check color contrast ratios to make your content user-friendly.
While inline CSS can be helpful for quick testing, using an external stylesheet is the best approach for most projects. External stylesheets allow you to keep your design separate from your HTML structure, which makes your code cleaner and easier to maintain. For example, if you want to change the same background across multiple pages, you can do it in one place—the CSS file—instead of updating each HTML page individually. This also helps with website performance, since external CSS files can be cached by browsers. In contrast, inline CSS increases redundancy and makes your code harder to manage in the long run.
Yes, you can use JavaScript to dynamically change the background image when a user interacts with your page. For example, you could add a button that switches between light and dark themes by changing the style.backgroundImage property. Here’s a simple example:
document.getElementById("btn").onclick = function() {
document.body.style.backgroundImage = "url('new-background.jpg')";
};
This creates an interactive experience for the user. You can also add animations or transitions to make the switch smooth. Dynamic background changes are common in galleries, portfolio websites, and dashboards where user choice impacts the design. Always remember to provide fallback images in case the main image doesn’t load properly.
Adding a gradient overlay is a popular way to improve readability while keeping the image visible. You can combine gradients and images in the background-image property using CSS. For example:
div {
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url('photo.jpg');
}
Here, the gradient creates a transparent layer that darkens the image slightly, making text on top more visible. You can adjust the colors and opacity of the gradient to match your website’s theme. This method works well for banners, hero sections, or promotional blocks where both the image and the text need to stand out.
Yes, you can use SVG files as background images, and they are especially useful for icons, logos, or vector-based graphics. SVGs scale perfectly at any resolution without losing quality, making them a great choice for responsive designs. To use an SVG as a background, simply point to the .svg file in your CSS:
div {
background-image: url('logo.svg');
}
You can also embed inline SVG code directly if you want to style it further with CSS. The main advantage of SVGs is that they are lightweight and crisp on all screen sizes, unlike raster images that may pixelate. Just check browser compatibility for advanced SVG features to ensure smooth performance.
In single-page applications (SPAs), background images may flicker if they are being re-rendered or not cached properly. This happens because JavaScript often reloads elements as you move between views. To avoid this, ensure your images are cached by the browser using HTTP caching or preload tags. Another solution is to apply your background styles in a persistent root CSS file instead of attaching them to components that reload frequently. Minimizing DOM updates and optimizing asset loading also help prevent flickering. In SPAs, performance is critical, so efficient image handling is key.
Different browsers sometimes interpret CSS rules slightly differently, which can affect how background images are scaled. To fix this, always use background-size: cover; or contain; depending on your design needs. Adding vendor prefixes like -webkit-, -moz-, or -o- for older browser versions can also help. For example:
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
Also, test your site on Chrome, Firefox, Safari, and Edge to ensure the image looks consistent. Avoid conflicting CSS rules that may override your scaling, and consider responsive breakpoints to handle specific devices.
You cannot directly animate the background-image property in CSS, but you can simulate transitions by layering multiple backgrounds and animating their opacity. One common approach is to create a ::before or ::after pseudo-element with another background image and then fade it in or out. For example:
div::before {
content: "";
background-image: url('second.jpg');
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
div:hover::before {
opacity: 1;
}
This creates a smooth transition effect when hovering. While it’s not true animation of the background image itself, it gives a similar experience and is commonly used in modern web design.
Yes, CSS allows you to apply multiple background images to a single element. You simply list them in the background-image property separated by commas. For example:
div {
background-image: url('texture.png'), url('pattern.svg');
background-position: center, top left;
background-repeat: no-repeat, repeat;
}
The first image listed will appear on top, while others will layer behind it. This is useful if you want to combine textures, patterns, and images for a richer design. Just be mindful of performance, as multiple large images can slow down page loading.
To keep a background image fixed while the rest of the page scrolls, you can use the CSS property background-attachment: fixed;. For example:
body {
background-image: url('scenery.jpg');
background-attachment: fixed;
background-size: cover;
}
This creates a parallax-like effect where the image stays still and the content moves. It’s visually appealing, especially for landing pages. Keep in mind that on mobile devices, some browsers disable background-attachment: fixed; due to performance issues. In such cases, alternative design techniques may be required.
Yes, you can use the background-position property to control exactly where your background image appears within its container. For example:
div {
background-image: url('photo.jpg');
background-position: top right;
}
You can specify positions like top, bottom, center, left, and right, or even use percentage values for more precise placement. This helps if your image contains important visual elements, like a person or logo, that should remain visible and not get cropped. Always test across different screen sizes to ensure the positioning works well.
Background images can slow down a website if not optimized properly. To reduce loading time, start by compressing your images using tools like TinyPNG or ImageOptim. Choose the right format—JPEG for photos, PNG for transparent images, and WebP for modern high-quality compression. You can also use CSS sprites to combine multiple small images into one file, reducing server requests. Another tip is lazy-loading, where images load only when they are about to appear on the user’s screen. Optimizing background images improves both site performance and SEO rankings.
Yes, you can directly set a background image using inline CSS in the style attribute of an HTML tag. For example:
<body style="background-image: url('image.jpg');">
This is quick for testing or small projects. But for larger websites, inline CSS is not recommended because it mixes design with structure and makes updates harder. Inline styles also don’t take advantage of browser caching the way external stylesheets do. It’s better to move background settings into a CSS file once your design is finalized.
Yes, you can use an HTML5 <video> element as a background instead of a static image. This is often done for modern landing pages or promotional websites. For example:
<video autoplay muted loop id="bg-video">
<source src="background.mp4" type="video/mp4">
</video>
You can then use CSS to position it behind your content. Videos can make your site look engaging, but they come with performance trade-offs. Large video files can slow down loading times, especially on mobile devices. Always compress video files, set autoplay to muted (since browsers block unmuted autoplay), and provide a fallback image in case the video doesn’t load.
If you want an image to repeat across the page, you can use the background-repeat property. By default, background images repeat both horizontally and vertically, but you can control this. For example:
body {
background-image: url('pattern.png');
background-repeat: repeat-x;
}
This repeats the image only along the x-axis. For both axes, use repeat. For no tiling at all, use no-repeat. Tiled backgrounds are commonly used for small textures or patterns to reduce file size and still cover large areas of a webpage. Just make sure your image is seamless, so the repetitions blend smoothly.
Yes, you can use CSS variables to manage background images more efficiently. For example:
:root {
--hero-bg: url('banner.jpg');
}
.hero {
background-image: var(--hero-bg);
}
This lets you define your background image once and reuse it across multiple elements. If you need to update the image later, you only change it in one place. This approach is especially useful in large projects or when working with themes, where the same image may be used in multiple sections. It makes your code cleaner, more maintainable, and easier to scale.
To center both the background image and text, you can combine CSS background properties with flexbox. For example:
.container {
background-image: url('photo.jpg');
background-size: cover;
background-position: center;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Here, the background image is centered with background-position: center;, while the text inside the container is centered both vertically and horizontally using flexbox. This technique is perfect for hero sections, landing pages, or call-to-action blocks. It ensures both the text and background work together visually.
References:
https://www.zenrows.com/blog/javascript-usage-statistics
https://cloudinary.com/guides/front-end-development/css-background-image-quick-tutorial-and-3-automation-tips
900 articles published
Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources