在Bootstrap 4列中配置响应式图片:srcset与sizes属性求助
Got it, let's work through this together to get those srcset and sizes attributes right for your Bootstrap layout.
First, we’ll break down each image since their visibility and render widths differ:
1. First Image (Visible on All Screens)
This image lives in col-12 col-lg-6, so it takes full width on screens below 992px, and half width on screens 992px and above. We’ll map your tested render widths to media queries in the sizes attribute, and pair that with your generated image variants in srcset.
Here’s the final tag:
<img src="example-image-1-800px.jpg" class="img-fluid" alt="Your image description" srcset=" example-image-1-350px.jpg 350w, example-image-1-350px-2x.jpg 700w, example-image-1-500px.jpg 500w, example-image-1-500px-2x.jpg 1000w, example-image-1-650px.jpg 650w, example-image-1-650px-2x.jpg 1300w, example-image-1-800px.jpg 800w, example-image-1-800px-2x.jpg 1600w " sizes=" (min-width: 1500px) 680px, (min-width: 1200px) 535px, (min-width: 992px) 440px, (min-width: 768px) 610px, (min-width: 576px) 544px, (min-width: 414px) 382px, calc(100vw - 20px) " >
What each part does:
src: Fallback for older browsers that don’t supportsrcset.srcset: Lists all your image variants with their intrinsic widths (thewunit tells the browser how wide the image file is). The-2xversions are for high-DPI screens (like Retina displays), since their width is double the base size.sizes: Tells the browser how wide the image will render at each viewport breakpoint. The last value (calc(100vw - 20px)) is the default for screens smaller than 414px, accounting for minimal container padding.
2. Second Image (Visible Only on Screens ≥992px)
This image is in col-6 d-none d-lg-block, so it only shows up on large and extra-large screens. Its render widths are limited to the lg/xl/xxl breakpoints:
Final tag:
<img src="example-image-2-800px.jpg" class="img-fluid" alt="Your image description" srcset=" example-image-2-350px.jpg 350w, example-image-2-350px-2x.jpg 700w, example-image-2-500px.jpg 500w, example-image-2-500px-2x.jpg 1000w, example-image-2-650px.jpg 650w, example-image-2-650px-2x.jpg 1300w, example-image-2-800px.jpg 800w, example-image-2-800px-2x.jpg 1600w " sizes=" (min-width: 1500px) 680px, (min-width: 1200px) 535px, (min-width: 992px) 440px " >
Key notes here:
- The
sizesattribute only includes breakpoints where the image is visible (992px and above). - The
srcsetuses the same structure as the first image—just swap out the image filename prefix for your second image.
Reusing These Tags
To reuse these for other images, just:
- Replace the
srcvalue with your base image (800px is a safe fallback). - Update all filenames in
srcsetto match your new image variants. - Adjust the
alttext for accessibility. - If your render widths change for other layouts, tweak the
sizesmedia query values accordingly.
内容的提问来源于stack exchange,提问作者hormigaz

