Performance: Background size
Background size affects how background images are scaled and rendered, impacting paint and layout performance.
Jump into concepts and practice - no test required
background-image: url('optimized-image.jpg'); background-size: 100% 100%;
background-image: url('large-image.jpg'); background-size: cover;
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| background-size: cover with large image | none | none | high (large paint area) | [X] Bad |
| background-size: 100% 100% with optimized image | none | none | low (small paint area) | [OK] Good |
background-size: cover; do to a background image?cover behaviorcover scales the background image to fill the entire element area, even if some parts get cropped.contain fits the whole image inside without cropping, and repeating is controlled by background-repeat.cover = fills and crops [OK]contain scales the image to fit inside the element fully without cropping.cover crops, fill and stretch are invalid values for background-size.div {
width: 200px;
height: 100px;
background-image: url('flower.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
What will the background image look like inside the div?background-size: contain; effectbackground-repeat: no-repeat; prevents tiling, and background-position: center; centers the image. So empty space may appear if aspect ratios differ.div {
background-image: url('tree.jpg');
background-size: 100%;
background-repeat: no-repeat;
}
What is the problem?background-size: 100%; meaningbackground-repeat: no-repeat; disables tiling correctly, and background-size accepts percentages.background-size: 100%; only sets width, height is auto, so it may not fill the entire element. -> Option Acontain fits whole image but may leave empty space; cover fills but crops; 100% 100% stretches whole image to exactly fill without cropping or space; auto repeat tiles.background-size: 100% 100%; to stretch image exactly. -> Option D100% 100% fills exactly, no crop [OK]