Learn in this tutorial how to set the images you add to a post or page to be centered by default with a little bit of code.
You’ve probably noticed that when you add an image to a post or page, by default, it is displayed left aligned (even if the alignment setting is ‘none’).
You can change this setting easily from the block’s toolbar, but if you prefer to always display them centered it can be a bit time consuming to change it manually.
In this tutorial I will explain a very simple way to get the default setting to be the centered image by creating a block variation.
Here’s how to do it.
Steps to create an image block variation that displays images centered by default
1. Register a new block variation
The first thing you have to do is to register the new variations.
To do this create a file called block-variations.js inside your theme /assets/js/ folder (if it doesn’t exist you can create it) and add the following code:
To see this and another 1097 code snippets of this website, login or subscribe here.
The above code variation contains the following fields:
core/image
: the block for which we are creating the variation.isDefault
: beingtrue
indicates that it is a default variation.attributes
: the block attributes.
In this case, neither name
nor label
are necessary since you are not creating a new variation, but modifying the default one.
We only use one attribute:
align
: the type of alignment of the image (by default'none'
).
We set it to 'center'
, so that this is the default setting when a new image block is added.
You can see that for practical purposes the new variation you have created replaces the native block with the new settings.
2. Enqueue the new block variations
Once you have the file where you have registered the styles, you must enqueue them to the theme. To do this add the following snippet to the end of functions.php:
To see this and another 1097 code snippets of this website, login or subscribe here.
You can see that this is a very simple process and can save you (or your client) a lot of time.
This is a simple example that can inspire you to create your own default block variations.
By the way, you can see the specific attributes that each block has in the official documentation.
Conclusions
Are you tired of having to change the alignment of images every time you add one? Now you know how to change the default setting so that new images are centered by default.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂