Use WordPress Block Attributes As CSS Variables
Utilize WordPress block attributes as CSS variables to completely customize the styling of your frontend UI.

In this post I will show you a guided example of utilizing WordPress block attributes as CSS variables to allow better styling control of your WordPress block plugin UI.

Below is a post I created that shows how to implement CSS variables in case you need a refresher on how to include them in your stylesheets.

Also I need to include this post about styling WordPress blocks with CSS. This helped me create a more clean solution. My previous solution worked flawlessly by just passing the attributes and styling the elements individually in their own defined style parameters. More code but worked.

Pass WordPress Block Attributes For CSS Variables

WordPress Block Plugin Components

WordPress attributes are basically variables that are used in the block plugin to control the way your block element will appear to the user in the UI. They can be numeric values, strings, arrays or objects.

When you create a new WordPress block plugin, you will have a few stylesheets.

Style.scss

This is used in the frontend UI and in the editor while creating either page or post that you are including the block plugin for.

Editor.scss

This is used in just the editor while creating either page or post that you are including the block plugin for.

Note

In my case, I wanted the UI to be the same while in the edit mode as well as the frontend UI. I only utilized the Style.scss to customize the element.

Process

We will create an editable attribute in the block.json file.

Then we will create an array similar to the syntax used in CSS to introduce variables to hold block attributes as CSS variables.

This array is passed into the blockProps of the block plugin.

In the rendering of the frontend, done with dynamic rendering, we will access the style array via PHP when calling for the block wrapper.

I have created a simple example below that changes the background color of the element.

Note

This could be done a little differently if this is your end result. If you just want to change the background color of the main wrapper element for your block plugin, you could set a support attribute in block.json like this below.

	"supports": {
	  "color": {
		  "background": true,
		}
	},

The method above is built into WordPress block plugin editor system and does most of the "heavy lifting" for you.

Code

Creation

First we will create a new plugin to hold our project.

Navigate to your WordPress plugin directory.

Β <system_drive>\wordpress\wp-content\plugins

We will install new project using npx in the command prompt.

npx @wordpress/create-block@latest

This will be a guided prompted based creation of a new WordPress plugin.

Below an example of my answers to the prompts.

Navigate to your WordPress plugin page and your plugin should be listed. Activate it.

Back at your command prompt, change current directory to the directory of the plugin you just created. In my case I need to do the following.

cd my-custom-blocks

Now you will need to start npm to sync your project as you edit.

npm run start

We are ready to start editing the block plugin to utilize block attributes as CSS variables.

Block.JSON

This is the backbone of your project. It holds all the important file association and the naming convention for your block plugin. Here we will make a few changes.

We will need to add the attributes array. Then create a new attribute variable. Also give it a default value in HEX.

	"attributes": {
		"bgColor": {
			"type": "string",
			"default": "#219b8b"
		}
	},

I am doing this using dynamic rendering, so we will need to add a frontend UI page named render.php.Β 

	"render": "file:./render.php",
All together, your newly edited block.json should look similar to this.
{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "r2creations24/my-custom-blocks",
	"version": "0.1.0",
	"title": "My Custom Blocks",
	"category": "widgets",
	"icon": "smiley",
	"description": "Custom blocks created by R2creations24.",
	"example": {},
	"attributes": {
		"bgColor": {
			"type": "string",
			"default": "#219b8b"
		}
	},
	"supports": {
		"html": false
	},
	"textdomain": "my-custom-blocks",
	"editorScript": "file:./index.js",
	"editorStyle": "file:./index.css",
	"render": "file:./render.php",
	"style": "file:./style-index.css",
	"viewScript": "file:./view.js"
}

Save.js

Since we will be utilizing dynamic rendering, we will just pass null here. You could make this work in static rendering, just don't return null. You will need to create an exact replicate of the UI in the edit.js in this file.

export default function save() {
	return null;
}

Edit.js

This is where the magic happens. We will create the editor UI, function to set the attribute to new value when changed as well as build a method to pass the block attributes as CSS variables.

We will need to add the necessary imports to utilize the libraries in the block.

import { __ } from '@wordpress/i18n';

import { 
	useBlockProps,
	PanelColorSettings,
	InspectorControls
 		} from '@wordpress/block-editor';

import { PanelBody } from '@wordpress/components';

import './editor.scss';

Next we will create a variable to use that holds the attribute in a way that CSS will be able use it as a variable. Passing this to the blockProps will allow you to view the changes in the editor.

	const newStyle = {
        "--bg-color": attributes.bgColor
    };

    const blockProps = useBlockProps( { style: newStyle } );

I created a function to set the new color. Deselects the color, the color is passed to the function as undefined. I set the default color if the value is passed as undefined.

	function setBgColor(value){
        if(value === undefined){
            setAttributes({bgColor: "#219b8b"});
        } else {
             setAttributes({bgColor: value});
        }
    }

Lastly, we will create the UI for the editor. This will have the InspectorControls that will be in the right pane to edit the block as well as the main DOM element. They are wrapped in a parent element which is a fragment defined as <>...</>.

		<>
		    <InspectorControls>
                <PanelBody title={ __( 'Settings', 'my-custom-blocks' ) }>
                    <PanelColorSettings
                        title = { __('Configure Color')}
                        colorSettings={
                            [
                                {
                                    value: attributes.bgColor,
                                    onChange: (value) => setBgColor(value),
                                    label: __('Background Color')
                                }
                            ]
                        }
                    />

                </PanelBody>
            </InspectorControls>
		<p { ...blockProps }>
			{ __(
				'My Custom Blocks – hello from the editor!',
				'my-custom-blocks'
			) }
		</p>
		</>

All together you should have this.

import { __ } from '@wordpress/i18n';

import { 
	useBlockProps,
	PanelColorSettings,
	InspectorControls
 		} from '@wordpress/block-editor';

import { PanelBody } from '@wordpress/components';

import './editor.scss';

export default function Edit( { attributes, setAttributes } ) {

	const newStyle = {
        "--bg-color": attributes.bgColor
    };

    const blockProps = useBlockProps( { style: newStyle } );

	function setBgColor(value){
        if(value === undefined){
            setAttributes({bgColor: "#219b8b"});
        } else {
             setAttributes({bgColor: value});
        }
    }

	return (
		<>
		    <InspectorControls>
                <PanelBody title={ __( 'Settings', 'my-custom-blocks' ) }>
                    <PanelColorSettings
                        title = { __('Configure Color')}
                        colorSettings={
                            [
                                {
                                    value: attributes.bgColor,
                                    onChange: (value) => setBgColor(value),
                                    label: __('Background Color')
                                }
                            ]
                        }
                    />

                </PanelBody>
            </InspectorControls>
		<p { ...blockProps }>
			{ __(
				'My Custom Blocks – hello from the editor!',
				'my-custom-blocks'
			) }
		</p>
		</>
	);
}

Render.php

This is the frontend for the user. We are capturing the attribute value and applying it as a CSS variable. Then we pass it to the WordPress block plugin wrapper.

<?php

 $bgColor = $attributes['bgColor'];

 $style = "--bg-color: ".$bgColor.";";

?>
<p <?php echo get_block_wrapper_attributes(array("style" => $style)); ?>>
    Hello from Render.PHP.....excited?!?
</p>

Style.scss

Lastly we just need to implement the CSS variable name defined in both the edit.js and render.php and apply it to the element we want. In this case, we just want to apply it to the main block plugin DOM elements background.

.wp-block-r2creations24-my-custom-blocks {
	background-color: var(--bg-color);
	color: #fff;
	padding: 2px;
}

Result

Hope this was useful.