CSS Backgrounds allow you to change the background appearance of HTML elements. You can add background colors, images, gradients, and control how backgrounds are positioned and displayed.
Background properties help you create attractive sections, cards, banners, and complete webpage layouts.
CSS Background Color
The background-color property sets the background color of an element.
<style>
.box {
background-color: lightblue;
padding: 20px;
}
</style>
<div class="box">
Welcome to Web4Learners!
</div>
In this example, the <div> element receives a light-blue background. The padding property adds space inside the box.
CSS Background Image
The background-image property adds an image behind an element’s content.
.hero {
background-image: url("background.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
min-height: 300px;
}
Here, url() specifies the image file. The cover value scales the image to cover the available area, while center positions it in the middle. The no-repeat value prevents the image from repeating.
CSS Background Repeat
By default, background images may repeat to fill an element. You can control this behavior using background-repeat.
body {
background-image: url("pattern.png");
background-repeat: repeat-x;
}
Common values include:
repeat: Repeats the image horizontally and vertically.repeat-x: Repeats the image horizontally.repeat-y: Repeats the image vertically.no-repeat: Displays the image without repeating.
CSS Background Position and Size
The background-position property controls where an image appears, while background-size determines its dimensions.
.banner {
background-image: url("banner.jpg");
background-position: center top;
background-size: cover;
}
The image is positioned at the top center and scaled to cover the banner.
CSS Background Shorthand
You can combine several background properties into a single declaration.
.hero {
background: #1d4ed8 url("hero.jpg") center / cover no-repeat;
}
This shorthand specifies the background color, image, position, size, and repeat behavior.
CSS Background Gradients
CSS gradients create smooth transitions between colors without requiring a separate image file.
.card {
background: linear-gradient(135deg, #2563eb, #9333ea);
color: white;
padding: 24px;
}
This example creates a diagonal gradient from blue to purple.
CSS Backgrounds are useful for designing banners, content sections, buttons, and page layouts. Combine them with CSS Colors and CSS Selectors to style specific elements across your website.
1 thought on “CSS Backgrounds”
Comments are closed.