Try the suggestion below:
This assumes the <figure>
element holding an image has a data-display-alignment attribute to match the alignment class applied attached that is somehow surfaced as a parameter in the wp_calculate_image_sizes
hook:
/**
* Add custom image sizes attribute to enhance responsive image functionality
* for content images.
*
* @param string $sizes A source size value for use in a 'sizes' attribute.
* @param array $size Image size. Accepts an array of width and height
* values in pixels (in that order).
* @param string $data-display-alignment The alignment of the image.
* @return string A source size value for use in a content image 'sizes' attribute.
*/
function my_content_image_sizes_attr( $sizes, $size, $alignment ) {
$width = $size[0];
// If image is as wide as main content, nothing special is needed.
if ( 720 <= $width ) {
$sizes="100vw";
} else {
// Images displayed inside the regular content area.
$sizes="(min-width: 720px) 720px, 100vw";
// Wide images: 720+50% of the available extra space.
if ( 'wide' === $alignment ) ) {
$sizes="(min-width: 720) calc(50% + 720px), 100vw";
}
// Full images: 100% of the available extra space.
if ( 'wide' === $alignment ) ) {
$sizes="100vw";
}
// If there's a sidebar kicking in at 720px and taking up 25% of the available width.
if ( is_active_sidebar( 'sidebar-1' ) ) {
// Images displayed inside the regular content area.
$sizes="(min-width: 720px) 720px, 100vw";
// Wide images
if ( 'wide' === $alignment ) ) {
$sizes="(min-width: 960px) calc(50% + 720px), (min-width: 720px) 75vw, 100vw";
}
// Full images
if ( 'wide' === $alignment ) ) {
$sizes="(min-width: 720px) 75vw, 100vw";
}
}
}
return $sizes;
}
add_filter( 'wp_calculate_image_sizes', 'my_content_image_sizes_attr', 10, 3 );
Source: https://github.com/WordPress/gutenberg/issues/6131
Here’s another option:
/**
* Configure the "sizes" attribute of images.
*/
function THEMENAME_content_image_sizes_attr($sizes, $size) {
$width = $size[0];
if ($width > 640) {
return '(min-width: 840px) 640px, (min-width: 720px) calc(100vw - 200px), 100vw';
} else {
return $sizes;
}
}
add_filter('wp_calculate_image_sizes', 'THEMENAME_content_image_sizes_attr', 10 , 2);
Source: https://www.malthemilthers.com/responsive-images-and-how-to-implement-them-in-wordpress/