Ben is a lifelong Nintendo fan who likes to build websites, and make video games. He buys way too much Lego.
Last week Keith Devon asked if anyone knew how to fix Gutenbergs floated image blocks. For some reason the floated image gets wrapped in a containing div.
I’m not sure why this is done, but the code is right there cherry picking the blocks with an alignment and adding an extra wrapper. This makes floating and positioning content difficult since the positional controls are added inside the container.
Simon Blackbourn suggested using the
render_block filter to tweak the html, and so that’s what I did. The code ended up being very simple, it’s basically just a handful of string replacements.
What the code does is first check if we’re using the Image block. We could simplify this in WP 5.7 with the new
We then loop through the possible alignments and check to see if the current block contains one of them. If it does then we first remove the old alignment, then replace the wrapper class with the alignment we removed – shifting the alignment onto the wrapper. Finally I removed any empty class attributes.
Why does this happen?
The wrapper is added so that certain alignment situations happen, but they also mean that others can’t happen. There’s a full explanation on this Gutenberg Github issue. The Github issue was very active this time last year but has now stalled, which suggests to me that it won’t be addressed; but I hope I’m wrong since improving this would make theming a lot simpler.
I’m now wondering about adding this to Toolbelt along with fixes for any other blocks that have funky rendering behaviours. For example the Pullquote and Blockquote blocks have different wrappers that make styling the two blocks consistently a pain, so maybe something could be done to improve that as well.