background-size & background-position
Background-size controls how large the background image is. Background-position controls where it's placed. Together they control image behavior and visual presentation.
Background Size Values
Value | Behavior | Use Case |
|---|---|---|
auto | Original size | Small images |
cover | Fill container, crop excess | Hero images |
contain | Fit in container | Logos, icons |
100% 100% | Stretch to fill | Textured backgrounds |
CSS
/* Background size values */
.auto {
background-size: auto;
/* Original image size */
}
.cover {
background-size: cover;
/* Fill container, crop excess */
}
.contain {
background-size: contain;
/* Fit entire image, may have gaps */
}
.stretch {
background-size: 100% 100%;
/* Stretch to fill container */
}
.specific {
background-size: 200px 100px;
/* Specific width and height */
}Background Position
CSS
/* Position keywords */
.element {
background-position: center;
background-position: top;
background-position: bottom;
background-position: left;
background-position: right;
}
/* Combined keywords */
.element {
background-position: top center;
background-position: bottom right;
background-position: center left;
}
/* Pixel values */
.element {
background-position: 10px 20px;
/* 10px from left, 20px from top */
}
/* Percentage values */
.element {
background-position: 50% 50%;
/* Center (50% from left, 50% from top) */
}Practical Examples
CSS
/* Hero image that fills viewport */
.hero {
background-image: url('hero.jpg');
background-size: cover;
background-position: center;
height: 100vh;
}
/* Logo that fits in box */
.logo-box {
background-image: url('logo.png');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
width: 200px;
height: 100px;
}
/* Tiled pattern */
.pattern {
background-image: url('pattern.png');
background-size: 40px 40px;
background-repeat: repeat;
}Note
Background-size: cover for images, contain for logos. Background-position: center for focal points. Useful for responsive images without img tags.
Next
Background repeat: [background-repeat & origin & clip](/css/background-repeat).