Welcome back to CodeYourCraft! In our last lesson, we learned the basics of CSS. Today, we're diving deeper into the world of CSS backgrounds. Let's get started!
background Property šThe background property is used to set the background of an HTML element. It can be used to set a background color, an image, or both.
/* Set background color */
div {
background-color: blue;
}
/* Set background image */
div {
background-image: url('image.jpg');
}
/* Set background with both color and image */
div {
background: blue url('image.jpg');
}š” Pro Tip: Always specify the background-color when using an image. This ensures the element has a background even if the image fails to load.
The background-attachment property determines whether the background image should scroll with the content or remain fixed.
/* Fixed background */
div {
background-attachment: fixed;
}
/* Scrolling background */
div {
background-attachment: scroll;
}The background-repeat property controls how the background image should be repeated.
/* No repetition */
div {
background-repeat: no-repeat;
}
/* Repeat both horizontally and vertically */
div {
background-repeat: repeat;
}
/* Repeat horizontally only */
div {
background-repeat-x: repeat;
}
/* Repeat vertically only */
div {
background-repeat-y: repeat;
}The background-size property determines the size of the background image.
/* Default size */
div {
background-size: auto;
}
/* Set fixed width and height */
div {
background-size: 200px 300px;
}
/* Cover the entire element */
div {
background-size: cover;
}
/* Contain the image within the element */
div {
background-size: contain;
}The background-position property sets the position of the background image within the element.
/* Center the image */
div {
background-position: center;
}
/* Position image 100px from the left and 200px from the top */
div {
background-position: 100px 200px;
}Now, let's put our new CSS background skills to the test by designing a simple web page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Web Page</title>
<style>
body {
background-color: lightblue;
background-image: url('background.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
</style>
</head>
<body>
<!-- Your content goes here -->
</body>
</html>Which CSS property is used to set the size of a background image?
That's it for today! In the next lesson, we'll explore more CSS properties to help you create beautiful and functional web pages. Remember, practice makes perfect!
Stay curious and keep coding! š”