HTML Background Images
Background images can enhance the look and feel of a webpage. Instead of using the <img>
tag, background images are typically applied using CSS. This approach keeps HTML structure clean and separates design from content. You can control positioning, repeating, and size of background images to create appealing designs.
Key Topics
- Applying a Basic Background Image
- A Page with Background Image
- Background Images in a Table Cell
- Key Takeaways
Applying a Basic Background Image
Example: Using inline CSS style to set a background image on a div.
<div style="background-image:url('images/TryMeYourSelf-logo-head.png'); width:300px; height:200px;"></div>
A Page with Background Image
This example demonstrates how to apply a background image to the entire page using CSS in the <style>
section. A full code demonstration is provided below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Image Example</title>
<style>
body {
background-image: url('images/TryMeYourSelf-logo-3.png');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
</style>
</head>
<body>
<h1>Welcome!</h1>
<p>This page has a background image applied using CSS.</p>
</body>
</html>
Explanation: The background-image
, background-position
, and background-size
properties control how the image appears behind the page content. Using CSS for backgrounds keeps your HTML markup focused on structure and semantics.
Background Images in a Table Cell
This demonstration shows how to apply a background image to a specific table cell. Another full code sample is provided below.
<h2>Background in a Table Cell</h2>
<table border="1" style="border-collapse:collapse; width:50%;">
<tr>
<td style="background-image:url('images/TryMeYourSelf-logo-2.png'); background-size:contain; background-repeat:no-repeat; height:150px;">
Text over a background image
</td>
<td>Normal cell without background</td>
</tr>
</table>
Explanation: By applying a background image to a single table cell, you can highlight specific information or create a more engaging layout. The CSS properties control how the image fits and repeats.
Key Takeaways
- Use CSS to apply background images, separating style from HTML structure.
- Control background positioning, size, and repetition to achieve desired effects.
- Background images can be applied to any element, including the
<body>
or table cells. - Keep accessibility in mind: background images are decorative and should not contain crucial information without text alternatives.
- Experiment with different background properties to create visually appealing designs.