CSS Backgrounds

📚 Lesson 14 of 30  •  ⏱ 10 min read  •  Beginner

background-color

CSS
.box {
  background-color: #6c63ff;       /* hex */
  background-color: rgb(108,99,255);  /* rgb */
  background-color: rgba(0,0,0,0.5); /* semi-transparent */
  background-color: transparent;    /* no background */
}

/* Shorthand */
.box { background: #6c63ff; }

background-image

CSS
.hero {
  background-image: url('images/hero.jpg');
  background-size: cover;      /* fill container, may crop */
  background-position: center;  /* focus on center */
  background-repeat: no-repeat;
}

/* background-size options */
background-size: cover;    /* fill, maintain ratio, may crop */
background-size: contain;  /* fit inside, may leave gaps */
background-size: 100% 100%; /* stretch to fill exactly */
background-size: 300px;    /* fixed width */

Linear Gradients

CSS
/* direction, start-color, end-color */
.hero   { background: linear-gradient(to right, #6c63ff, #48aff0); }
.banner { background: linear-gradient(135deg, #667eea, #764ba2); }

/* With transparency — common for text overlays on images */
.overlay {
  background: linear-gradient(
    to bottom,
    transparent 0%,
    rgba(0,0,0,0.7) 100%
  );
}

/* Multi-stop */
.rainbow { background: linear-gradient(to right, red, orange, yellow, green, blue); }

Radial Gradients

CSS
.glow {
  background: radial-gradient(circle, #6c63ff 0%, transparent 70%);
}

.spot {
  background: radial-gradient(ellipse at top, #667eea, #764ba2);
}

Multiple Backgrounds

CSS
/* List backgrounds separated by comma — first is on top */
.card {
  background:
    linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)),  /* dark overlay */
    url('hero.jpg') center/cover no-repeat;             /* image */
}

background Shorthand

CSS
/* color  image  position/size  repeat  attachment */
.hero {
  background: #1a1a2e url('bg.jpg') center/cover no-repeat fixed;
}
/* fixed = parallax scrolling effect */