Calculate the correct content width for the Gutenberg editor
The WordPress Gutenberg editor allows you to customize and edit web page content according to the frontend design. Gutenberg will share the frontend design experience of the website into the editor. A good starting point is to get the correct content width from the frontend view inside the editor, which can vary depending on the options of the theme.
For example, the content width changes depending on whether a sidebar is displayed or not. Or if you can select between different content widths such as “wide”, “medium” or “narrow”.
What do we need for the right calculation of the content width?
Depending on which design options a theme offers, the basis for calculating a content width can be very different. In my example, the following points are important to correctly calculating the Gutenberg editor content width.
- Outer Content Width – The width of the entire web page area, which includes all elements such as header and footer.
- Inner Content Width – The width of the text area
the_content();
which could be “wide”, “medium” or “narrow”. - Sidebar Width – The width of the sidebar is also an important part because the width of the content is different, depending on the visible or hidden sidebar.
- Paddings – In addition, there are various paddings to the edge of the browser window, which slightly reduce the content width.
Calculate the content width of the website
The following function calculates the content width based on the listed points above and will later be used to get the correct content width for the Gutenberg editor.
The function calc_gutenberg_editor_content_width()
now gives us the correct width in a numerical value, which allows us to specify the correct content width of the Gutenberg editor, depending on the theme settings.
Pass the content width to the Gutenberg editor
We use the WordPress action enqueue_block_editor_assets
, which help us to output the correct content width via inline CSS. The dummy handler “block-editor-styles” is necessary in this case to apply the inline style with the function wp_add_inline_style( 'block-editor-style', $inline_css )
. Instead, of course, another handler from an existing block editor style can be used to output wp_add_inline_style().
The WordPress Gutenberg editor block class .wp-block {…}
is the correct CSS selector, which passes our content width to the blocks. With this additional code, you can now easily calculate the correct content width for the WordPress block editor on depending theme design options.