Using Background Images
Using background images.
Using background images in CSS is a common way to enhance the visual appeal of your web pages, we use the background-image property to specify or add background image in CSS
SYNTAX:
selector { background-image: url("path/to/image.jpg");}Basic Concepts
- Background Image Property: The
background-imageproperty is used to set a background image for an element. - URL: The image source is defined using the url() function.
- Background Properties: Other properties like
background-repeat,background-size,background-position, andbackground-attachmentare used to control the appearance and behavior of the background image
EXAMPLE:
Create a simple HTML structure with elements to which you will apply background images.
HTML CODE:
Create a simple HTML structure with elements to which you will apply background images.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Background Images in CSS</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <div class="background-example"></div> <div class="background-cover-example"></div> <div class="background-fixed-example"></div> </body></html>CSS CODE:
In your styles.css file, define the styles for each example.
/_ Example 1: Basic Background Image _/.background-example {width: 300px;height: 200px;background-image: url('path/to/your/image.jpg');background-repeat: no-repeat; /_ Prevents repeating of the image _/background-position: center; /_ Centers the image _/}
/_ Example 2: Background Image with Cover _/.background-cover-example {width: 300px;height: 200px;background-image: url('path/to/your/image.jpg');background-size: cover; /_ Scales the image to cover the entire element _/background-repeat: no-repeat;background-position: center;}
/_ Example 3: Fixed Background Image _/.background-fixed-example {width: 100%;height: 300px;background-image: url('path/to/your/image.jpg');background-size: cover;background-repeat: no-repeat;background-attachment: fixed; /_ Fixes the background image in place _/background-position: center;}Brief Explanation of Properties
- background-image: Specifies the URL of the image.
- background-repeat: Controls if/how the background image is repeated (e.g., repeat, repeat-x, repeat-y, no-repeat).
- background-position: Sets the initial position of the background image (e.g., left, center, right, top, bottom).
- background-size: Specifies the size of the background image (e.g., cover, contain, or specific dimensions).
- background-attachment: Sets whether the background image scrolls with the page (scroll) or is fixed in place (fixed).