Full width images are a sweet new feature that Gutenberg offers to WordPress theme developers. In order to enable these in your theme, it takes just a few lines of code.
Problem #1
By default, the Gutenberg Image Block only has the three classic alignment options: left-aligned, centered, and right-aligned.
- Gutenberg Default Image Alignment Options
Enabling Wide Images in the Gutenberg Editor
First, a bit of PHP. Add this to your theme’s functions.php, or wherever else you are adding your add_theme_support()
functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add Theme Support for wide and full-width images. | |
* | |
* Add this to your theme's functions.php, or wherever else | |
* you are adding your add_theme_support() functions. | |
* | |
* @action after_setup_theme | |
*/ | |
function jr3_theme_setup() { | |
add_theme_support( 'align-wide' ); | |
} | |
add_action( 'after_setup_theme', 'jr3_theme_setup' ); |
Now, you can find two new icons on your Image Gutenberg Block, wide-align, and full-width.
When one of these options is selected, it will display correctly in the editor. If you select wide-align, the image gets wider, and if you select full-width, the image fills the editor horizontally.
Wide Image Previews in the Gutenberg Editor
- A wide image in the Gutenberg Editor
- A full-width image in the Gutenberg Editor
Problem #2
There’s just one issue: Although WordPress adds special classes to the image markup, this doesn’t affect your actual theme styles.
- An unstyled full-width image in the Theme.
The Solution
To solve this, add your own CSS. Here’s a snippet I came up with:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.alignwide { | |
/* Set these margins to work with your own theme. */ | |
margin-left: -80px; | |
margin-right: -80px; | |
max-width: 100vw; | |
} | |
.alignfull { | |
margin-left: calc(-100vw / 2 + 100% / 2); | |
margin-right: calc(-100vw / 2 + 100% / 2); | |
max-width: 100vw; | |
} | |
.alignfull img { | |
width: 100vw; | |
} |
A few notes about the CSS:
calc()
tells the browser to calculate a value (usually) based on the screen size.vw
refers to “viewport width,” or screen width.
The Result
After the styles are applied:
- A wide-aligned image in the theme after adding the CSS.
- A full-width image in the theme after adding the CSS.
So, with less than 20 lines of code, you can add this powerful and attractive feature to your themes.
This was amazing and explained in an easy-to-understand matter. Thank you.
Great code and explanation I got this working in a matter of minutes. Many thanks