Creating a full-page background image is a simple way to add visual impact to your website. Here's the modern approach to make an image cover the entire viewport.
The Basic Technique
Use background-size: cover
to ensure the image covers the entire container:
html {
background: url("images/background.jpg") no-repeat center center fixed;
background-size: cover;
min-height: 100vh;
}
Understanding Background-Size Values
Cover - Scales the image to cover the entire container (most common):
.full-background {
background-size: cover;
/* Image fills container completely, may crop edges */
}
Contain - Scales the image to fit entirely within the container:
.fit-background {
background-size: contain;
/* Entire image visible, may leave empty space */
}
Better Approach for Modern Layouts
Instead of applying to html
, use a dedicated container:
.hero-section {
background: url("images/hero.jpg") no-repeat center center;
background-size: cover;
min-height: 100vh;
}
With Fallback Color
Always include a fallback background color:
.hero-section {
background-color: #2c3e50; /* Shows if image fails to load */
background-image: url("images/hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
min-height: 100vh;
}
The image will automatically scale to cover the full viewport while maintaining its aspect ratio.