媒体查询CSS代码优化求助
Hey there! Let's clean up your media query code to make it more maintainable, efficient, and better for your site's loading speed. Right now, you're repeating a lot of identical CSS properties across multiple media queries, and your breakpoints have some overlap that can cause confusion. Here's how to fix it:
Step 1: Extract Common Styles
First, move all the shared CSS properties for .Frontpage-image outside of your media queries. This way you don't repeat the same code over and over, making future edits way easier:
body, html { height: 100%; width: 100%; margin: 0; } .Frontpage-image { background-repeat: no-repeat; background-position: center center; background-size: cover; height: 100vh; }
Step 2: Simplify Media Query Logic (Mobile-First Approach)
You're targeting multiple breakpoints for the same desktop image, which is redundant. Using a mobile-first approach (start with mobile styles, then override for larger screens) will make your code cleaner and avoid conflicts:
/* Default: Mobile image (applies to screens <768px) */ .Frontpage-image { background-image: url("https://dit.be/wp-content/uploads/2021/01/mobiel-01.svg"); } /* Override for tablets and desktops (768px and up) */ @media only screen and (min-width: 768px) { .Frontpage-image { background-image: url("https://dit.be/wp-content/uploads/2021/01/desktop-01.svg"); } }
This replaces all your previous media queries with just one override. The landscape tablet query you had is unnecessary here—any tablet in landscape mode will have a width greater than 768px, so it will automatically use the desktop image.
Step 3: Boost Loading Speed Further
To really optimize image loading, consider these additional tweaks:
Use Modern Image Formats
SVG is great, but if you can, convert these images to WebP or AVIF formats (while keeping SVG as a fallback). These formats have smaller file sizes, which reduces load times significantly.
Avoid Unnecessary Image Downloads
One downside of using CSS background images is that browsers may still preload the desktop image on mobile devices. To prevent this, switch to using the <picture> element instead. This tells the browser to only load the image that matches the current screen size:
<picture> <!-- Desktop image for screens 768px and up --> <source media="(min-width: 768px)" srcset="https://dit.be/wp-content/uploads/2021/01/desktop-01.svg"> <!-- Mobile image (fallback for all screens) --> <img src="https://dit.be/wp-content/uploads/2021/01/mobiel-01.svg" alt="Frontpage hero image" class="Frontpage-image" > </picture>
Then adjust your CSS to style the <img> tag instead of a background:
.Frontpage-image { display: block; width: 100%; height: 100vh; object-fit: cover; }
This ensures mobile users only download the smaller mobile image, which will make your site load faster on slow networks.
内容的提问来源于stack exchange,提问作者TML

