Fixing the Gutenberg Block Editor alignfull Class with JavaScript So That Parent Elements Don’t Need Hidden Overflows So That You Can Use Sticky Elements When Your Browser Has Scroll Bars

David F. Choy
2 min readJul 30, 2021

--

Problem

WordPress theme developers can opt-in using the block editor with wide and full alignment classes. If you are doing this, you are likely putting block content into a centered column and then “breaking-out” as needed. In the alignfull case, the default strategy to expand a block to full width is to set the blocks’s width to 100% of the viewport and give the block some margins relative to itself.

.alignfull {
width: 100vw;
margin-left: calc(-100vw / 2 + 100% / 2);
margin-right: calc(-100vw / 2 + 100% / 2);
}

This strategy unfortunately causes horizontal scrolling on devices that show scrollbars that do not hover content (e.g. Windows with a mouse). To compensate for this behavior, theme developers hide overflows on parent divs, or on the document body.

.page {
overflow:hidden;
}

Unfortunately, hiding overflows like this breaks sticky divs. You might care. And, you might need an overflow for something else. Or not. Here’s my decidedly only-half-gross css variable javascript solution. Let me know if you come up with a pure CSS solution.

Only-Half-Gross CSS Variable JavaScript Solution

  1. Make a CSS Variable:
.alignfull {
--scroll-bar-half-width: 0px;
display:block;
max-width: 100vw;
margin-left: calc( calc(-100vw / 2 + 100% / 2) - var(--scroll-bar-half-width) );
margin-right: calc( calc(-100vw / 2 + 100% / 2) - var(--scroll-bar-half-width) );
}

2. Given an element called element or elements with the alignfull class, and a function to getScrollBarWidth() (here’s one), use JavaScript:

let scroll_bar_width = getScrollBarWidth();
let scroll_bar_half_width = scroll_bar_width/2;
let element_style = getComputedStyle(element);
let css_var_scroll_bar_half_width = element_style.getPropertyValue('--scroll-bar-half-width');
if ( scroll_bar_half_width+'px' !== css_var_scroll_bar_half_width ) {
element.style.setProperty('--scroll-bar-half-width',scroll_bar_half_width+'px');
}

You can put this in a function and call it on key events (and on load and every few seconds if you are distrustful of the world). If there are no scroll bars, you can set that variable back to 0.

--

--

No responses yet