Setting Focus Points on Images in Statamic
In my last article, we took a look at using image sizes in Statamic, as compared to WordPress. Here, we take a closer look at using image focus points, and how to use this for background images.
Follow along as I explore setting focus points in Statamic, if you’d rather just site back and relax. Watch it here:
Focus Points in Statamic
When editing an image, you can select the “Focal Point” option to choose where in the image this point should be. The default is 50-50, which is the coordinates as a percentage of the width and height, on the X and Y axes.
Once we have this selection made, this new value is available in our Antlers template when we want to make use of it. It’s especially useful when we want to use this image as a background image, by setting this as an inline style.
In our case, we want to set it as the background behind the page title so that it looks something like this:
Using the Focal Point in CSS
To set the background and make use of the focal point, we can output our markup like so:
<div
style="background-image: url({{ glide:banner }});
background-position: {{ banner:focus | background_position }};
">
... content can go here
</div>
Initially, the focus
value is just the raw data as stored in the YAML file containing the meta information for a given asset like this:
data:
focus: 26-60-1
alt: 'Cyclists next to their bikes on the sea wall'
This format isn’t particularly useful with CSS, hence the background_position
modifier. However, Antlers also provides a more convenient way to access this without the modifier, which is an already-formatted value specifically for this use case, called focus_css
.
<div
style="background-image: url({{ glide:banner }});
background-position: {{ banner:focus_css }};
">
... content can go here
</div>
Now, the modifier is not needed, and we can simplify our template code. This will result in an output that will look like this:
background-position: 26% 60%;
Now whenever the screen size or the container size is adjusted, this background position value ensures that the focus point always remains visible. No more guessing on the position I am aiming for with the browser dev tools - I can set the point visually when editing the asset from right within the Statamic control panel.
Easy peasy.