Skip to content

Instantly share code, notes, and snippets.

@felixarntz
Created April 25, 2024 19:12
Show Gist options
  • Save felixarntz/b0bbcf68df14b16b9c2f0f048b4680a4 to your computer and use it in GitHub Desktop.
Save felixarntz/b0bbcf68df14b16b9c2f0f048b4680a4 to your computer and use it in GitHub Desktop.
Allowing inline images in WordPress block themes to use `alignright` / `alignleft` classes (e.g. in Twenty Twenty-Three child theme)
<?php
/**
* Styles 'alignright' and 'alignleft' inline elements to appear within horizontal content width.
*/
function twentytwentythree_felixarntz_style_alignright_alignleft() {
$extra_css = 'body .is-layout-flow > :where(:not(.alignleft):not(.alignright):not(.alignfull)) > .alignright {';
$extra_css .= 'float: right;';
$extra_css .= 'margin-inline-start: 2em;';
$extra_css .= 'margin-inline-end: 0;';
$extra_css .= 'max-width: 40%;';
$extra_css .= '}';
$extra_css .= 'body .is-layout-constrained > :where(:not(.alignleft):not(.alignright):not(.alignfull)) > .alignright {';
$extra_css .= 'float: right;';
$extra_css .= 'margin-inline-start: 2em;';
$extra_css .= 'margin-inline-end: 0;';
$extra_css .= 'max-width: 40%;';
$extra_css .= '}';
$extra_css .= 'body .is-layout-flow > :where(:not(.alignleft):not(.alignright):not(.alignfull)) > .alignleft {';
$extra_css .= 'float: left;';
$extra_css .= 'margin-inline-start: 0;';
$extra_css .= 'margin-inline-end: 2em;';
$extra_css .= 'max-width: 40%;';
$extra_css .= '}';
$extra_css .= 'body .is-layout-constrained > :where(:not(.alignleft):not(.alignright):not(.alignfull)) > .alignleft {';
$extra_css .= 'float: left;';
$extra_css .= 'margin-inline-start: 0;';
$extra_css .= 'margin-inline-end: 2em;';
$extra_css .= 'max-width: 40%;';
$extra_css .= '}';
if ( is_admin() ) {
wp_add_inline_style( 'wp-block-library', $extra_css );
} else {
wp_add_inline_style( 'global-styles', $extra_css );
}
}
add_action( 'wp_enqueue_scripts', 'twentytwentythree_felixarntz_style_alignright_alignleft' );
add_action( 'enqueue_block_editor_assets', 'twentytwentythree_felixarntz_style_alignright_alignleft' );
@felixarntz
Copy link
Author

felixarntz commented Apr 25, 2024

This allows displaying inline images next to floating text without overflowing the content width constraints. The CSS should cover the various configurations this should be relevant for, following the block editor's core CSS.

To see the CSS in use:

  1. Add an inline image (not image block) at the beginning of a paragraph.
  2. Edit the paragraph's HTML and add either an alignright or alignleft CSS class to it.

See relevant discussion on Twitter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment