learn2kode.in

HTML – Backgrounds

HTML allows you to add background colors, images, and patterns to elements using CSS. Backgrounds make web pages more visually appealing and help highlight specific sections.

1. Background Color

Use the background-color property to set the background color of any HTML element.

Example

<body style="background-color: lightblue;">
    <h2 style="background-color: yellow;">Highlighted Heading</h2>
    <p style="background-color: lightgray;">This is a paragraph with a gray background.</p>
</body>

2. Background Image

You can apply a background image using the background-image property.

Example

<body style="background-image: url('background.jpg');">
    <h2>Page with Background Image</h2>
</body>

3. Background Repeat

Defines whether the background image should repeat.

Value Meaning
repeat Repeats both vertically & horizontally
repeat-x Repeats horizontally only
repeat-y Repeats vertically only
no-repeat No repetition

Example

<body style="background-image: url('bg.png'); background-repeat: no-repeat;">
</body>

4. Background Size

Controls how the image fits the element.

Value Description
auto Original image size
cover Covers entire area (may crop)
contain Fits inside area (may leave space)

Example

<body style="background-image: url('bg.jpg'); background-size: cover;">
</body>

5. Background Position

Defines where the background image appears.

Example

<body style="background-image: url('bg.jpg'); background-position: center;">
</body>

6. Multiple Backgrounds

You can apply more than one background image.

Example

<div style="
    background-image: url('img1.png'), url('img2.png');
    background-position: left top, right bottom;
    background-repeat: no-repeat, no-repeat;
">
    Multiple backgrounds applied
</div>

7. Shorthand Background Property

Combine all background properties into one line:

<body style="background: url('bg.jpg') no-repeat center/cover;">
</body>