Introduction
Welcome to Day 5 of our 30-day Gutenberg development series! Now that you have a basic understanding of how to build custom blocks and use attributes, it’s time to take your block development to the next level by adding custom styles and enhancing the visual presentation of your blocks.
In this article, we’ll explore advanced techniques for styling Gutenberg blocks, including how to apply CSS, use inline styles, and make your blocks responsive. By the end of this guide, you’ll be able to create beautifully designed blocks that blend seamlessly with any WordPress theme.
Why Advanced Styling is Important
Styling is a crucial part of block development. Well-styled blocks enhance the user experience, ensure consistency with a website’s theme, and make the blocks more engaging. By mastering advanced styling techniques, you can:
- Create visually appealing blocks that align with the website’s design.
- Ensure consistency across different themes and devices.
- Enable customization options for users who want to tweak the look and feel of blocks within the editor.
Step 1: Styling Blocks with CSS
The simplest way to style your blocks is by using CSS. Let’s start by adding custom styles for a block.
Using Block-Specific CSS
In your block’s folder (blocks/my-first-block/
), you should already have a style.css
file that we created earlier. We’ll now add more advanced styles to this file.
Open the style.css
file and update it with the following styles:
/* Styling the block container */
.wp-block-your-theme-my-first-block {
padding: 20px;
background-color: var(--wp--preset--color--white);
border: 2px solid var(--wp--preset--color--gray);
border-radius: 5px;
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
}
/* Styling the block content */
.wp-block-your-theme-my-first-block p {
font-size: 18px;
line-height: 1.6;
}
/* Responsive styles for smaller screens */
@media (max-width: 768px) {
.wp-block-your-theme-my-first-block {
padding: 15px;
font-size: 16px;
}
}
Explanation:
- Block Container Styling: We add padding, background color, and a border to the block container. The
var()
function is used to pull predefined theme colors, ensuring that your block adapts to the active theme’s palette. - Content Styling: The paragraph inside the block is styled for better readability with adjusted font size and line height.
- Responsive Styles: We define styles that adjust the block’s padding and font size for smaller screens (under 768px).
Step 2: Using Inline Styles for Dynamic Styling
In many cases, you’ll want to apply dynamic styles directly from the Block Editor, such as changing background colors or text alignment. For this, you can use inline styles within your block’s JavaScript code.
Let’s update the index.js
file to apply inline styles based on the block attributes.
Open index.js
and modify the edit
and save
functions to apply the inline styles dynamically:
import { registerBlockType } from '@wordpress/blocks';
import { RichText, InspectorControls, ColorPalette } from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
registerBlockType('your-theme/my-first-block', {
title: __('My First Block', 'your-theme'),
category: 'common',
icon: 'smiley',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
backgroundColor: {
type: 'string',
default: '#f5f5f5',
},
isBold: {
type: 'boolean',
default: false,
},
},
edit: (props) => {
const { attributes: { content, backgroundColor, isBold }, setAttributes } = props;
const onChangeContent = (newContent) => {
setAttributes({ content: newContent });
};
const onChangeBackgroundColor = (newColor) => {
setAttributes({ backgroundColor: newColor });
};
const onToggleBold = () => {
setAttributes({ isBold: !isBold });
};
return (
<>
<InspectorControls>
<PanelBody title={__('Block Settings', 'your-theme')}>
<ColorPalette
value={backgroundColor}
onChange={onChangeBackgroundColor}
/>
<ToggleControl
label={__('Bold Text', 'your-theme')}
checked={isBold}
onChange={onToggleBold}
/>
</PanelBody>
</InspectorControls>
<RichText
tagName="p"
value={content}
onChange={onChangeContent}
placeholder={__('Enter your text here...', 'your-theme')}
style={{
backgroundColor,
fontWeight: isBold ? 'bold' : 'normal',
padding: '20px',
borderRadius: '5px',
border: '1px solid #ddd'
}}
/>
</>
);
},
save: (props) => {
const { attributes: { content, backgroundColor, isBold } } = props;
return (
<RichText.Content
tagName="p"
value={content}
style={{
backgroundColor,
fontWeight: isBold ? 'bold' : 'normal',
padding: '20px',
borderRadius: '5px',
border: '1px solid #ddd'
}}
/>
);
},
});
Explanation:
- Inline Styles: We apply dynamic inline styles directly within the
RichText
component. These styles are based on block attributes likebackgroundColor
andisBold
. - Inspector Controls: We allow users to modify the background color and text weight (bold) from the block settings in the editor sidebar. These styles are applied dynamically in both the editor (
edit
function) and the front end (save
function).
Step 3: Making Your Blocks Responsive
Responsive design is key to ensuring that your blocks look great on all devices. To achieve this, we need to include media queries in the block’s CSS or handle responsiveness directly with JavaScript if attributes impact styling dynamically.
Here’s an example of how you can add responsive styles to your style.css
:
@media (max-width: 768px) {
.wp-block-your-theme-my-first-block {
padding: 15px;
font-size: 16px;
border-radius: 3px;
}
.wp-block-your-theme-my-first-block p {
font-size: 14px;
}
}
By using media queries, you ensure that the block adapts to different screen sizes, providing a better user experience on mobile devices.
Step 4: Integrating Block Styles with WordPress Themes
One of the key benefits of Gutenberg is that blocks can seamlessly integrate with a WordPress theme’s styles. To make sure your blocks inherit theme styles properly, use CSS variables and WordPress’s built-in theme support functions.
For example, in your style.css
, you can use the following CSS variables to match the active theme’s colors:
.wp-block-your-theme-my-first-block {
background-color: var(--wp--preset--color--white);
color: var(--wp--preset--color--black);
border-color: var(--wp--preset--color--gray);
}
These CSS variables are automatically populated by the active theme’s color palette, making your block style consistent across different themes.
Step 5: Enqueueing Block Styles for Both Front-End and Editor
To ensure your styles are applied both in the editor and on the front end, you’ll need to enqueue the styles properly in WordPress. This can be done in your theme’s functions.php
file.
function my_theme_enqueue_block_assets() {
wp_enqueue_style(
'my-first-block-editor',
get_template_directory_uri() . '/blocks/my-first-block/style.css',
array(),
filemtime(get_template_directory() . '/blocks/my-first-block/style.css')
);
}
add_action('enqueue_block_assets', 'my_theme_enqueue_block_assets');
This ensures that the style.css
file is loaded both in the WordPress editor and on the front end, providing a consistent appearance for your blocks.
Conclusion: Taking Block Styling to the Next Level
With these advanced styling techniques, your custom Gutenberg blocks can now be visually dynamic, responsive, and seamlessly integrated with any WordPress theme. By combining CSS styles, inline styles, and theme compatibility, you can ensure that your blocks not only function well but also look great across devices and themes.
Key Takeaways:
- Use block-specific CSS to style the layout and content of your blocks.
- Leverage inline styles to dynamically update block styling based on user input in the editor.
- Ensure your blocks are responsive by adding media queries and handling different screen sizes.
- Integrate your block styles with the WordPress theme’s color palette to maintain consistency across different themes.
- Properly enqueue block styles for both the editor and front-end to ensure your block appears as expected in all contexts.
In Day 6, we’ll explore how to use Inspector Controls and custom settings in greater detail to give users even more control over the appearance and behavior of their blocks. Stay tuned for more advanced Gutenberg techniques!
Leave a Reply