DEV Community

alok-38
alok-38

Posted on

Perfect way to create a background image using CSS

How to Add a Background Image in CSS

header {
    background-image: url(../images/bg-desktop-light.jpg); /* Image path */
    height: 300px; /* Fixed height for header */
    background-repeat: no-repeat; /* Don’t tile the image */
    background-position: center; /* Center the image */
    background-size: cover; /* Fill the header while keeping aspect ratio */
}
Enter fullscreen mode Exit fullscreen mode

This is good for

  • Full-cover hero sections or headers.
  • Keeping image cantered and responsive.

Tips for improvement / modern best practices

background: url(../images/bg-desktop-light.jpg) center/cover no-repeat;
Enter fullscreen mode Exit fullscreen mode

Responsive images

@media (max-width: 768px) {
  header {
    background-image: url(../images/bg-mobile-light.jpg);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)