Skip to content

Kirby 4.5.0

$file->srcset()

Create a srcset definition for the given sizes Sizes can be defined as a simple array. They can also be set up in the config with the thumbs.srcsets option.

$file->srcset(array|string|null $sizes = null): string|null

Parameters

Name Type Default
$sizes array|string|null null

Return type

string|null

Parent class

Kirby\Cms\File

Example

<img
src="<?= $image->url() ?>"
srcset="<?= $image->srcset([300, 800, 1024]) ?>" />

Modify width definition

$image->srcset([
  800  => '1x',
  1600 => '1.5x'
]);

More complex sizes options

The $sizes parameter also accepts an associated array of options:

$image->srcset([
    '1x' => [
        'width'  => 38,
        'height' => 38,
        'crop'   => 'center'
    ],
    '2x' => [
        'width'  => 76,
        'height' => 76,
        'crop'   => 'center'
    ],
    '3x' => [
        'width'  => 152,
        'height' => 152,
        'crop'   => 'center'
    ]
]);

Convert image format

$image->srcset([
  '400w'  => ['width' => 400, 'format' => 'webp'],
  '800w'  => ['width' => 800, 'format' => 'webp'],
  '1200w' => ['width' => 1200, 'format' => 'webp']
])
Since 4.0.0

Crop around focus point

Instead of passing a general crop area like 'center', you can set the crop option to true and Kirby will use each image's focus point:

$image->srcset([
    '1x' => [
        'width'  => 38,
        'height' => 38,
        'crop'   => true
    ],
    '2x' => [
        'width'  => 76,
        'height' => 76,
        'crop'   => true
    ]
]);

Define presets

Simple example

site/config/config.php
return [
  'thumbs' => [
    'srcsets' => [
            'default' => [300, 800, 1024],
            'cover' => [800, 1024, 2048]
        ]
  ]
];

Extended example

/site/config/config.php
return [
  'thumbs' => [
    'srcsets' => [
      'default' => [
        '800w' => ['width' => 800, 'quality' => 80],
        '1024w' => ['width' => 1024, 'quality' => 80],
        '1440w' => ['width' => 1440, 'quality' => 80],
        '2048w' => ['width' => 2048, 'quality' => 80]
      ]
  ]
  ]
];
// default preset
$image->srcset();

// particular preset
$image->srcset('cover');