CSS Backgrounds
CSS backgrounds allow you to set various properties on an element's background, such as color, image, position, size, and more. These properties help you style your elements to enhance the visual appeal of your web pages.
Background Color
The `background-color` property sets the background color of an element. You can use named colors, hex codes, RGB, RGBA, HSL, or HSLA values.
/* Background color examples */
.container {
background-color: lightgray; /* Named color */
}
.header {
background-color: #3490dc; /* Hex code */
}
.footer {
background-color: rgba(255, 99, 71, 0.5); /* RGBA */
}
Background Image
The `background-image` property sets one or more background images for an element. You can use image URLs or gradients.
/* Background image examples */
.banner {
background-image: url('banner.jpg'); /* Image URL */
background-size: cover; /* Cover the entire element */
}
.card {
background-image: linear-gradient(to right, #ff7e5f, #feb47b); /* Gradient */
}
Background Position
The `background-position` property specifies the position of the background image. You can use keywords (e.g., `top right`) or specific values.
/* Background position examples */
.banner {
background-position: center; /* Centered */
}
.card {
background-position: top left; /* Top left corner */
}
Background Size
The `background-size` property specifies the size of the background image. Common values include `cover`, `contain`, or specific dimensions.
/* Background size examples */
.banner {
background-size: cover; /* Cover the entire element */
}
.card {
background-size: 50% 50%; /* 50% width and height */
}
Background Repeat
The `background-repeat` property defines whether or not a background image should repeat. You can use values like `repeat`, `no-repeat`, `repeat-x`, or `repeat-y`.
/* Background repeat examples */
.banner {
background-repeat: no-repeat; /* Do not repeat */
}
.card {
background-repeat: repeat-x; /* Repeat horizontally */
}
Background Attachment
The `background-attachment` property sets whether a background image scrolls with the page or is fixed.
/* Background attachment examples */
.banner {
background-attachment: fixed; /* Fixed background image */
}
.card {
background-attachment: scroll; /* Scrolls with the content */
}