Building a Custom Block Part 4: Adding Styles and Custom Interactivity

By Ian Svoboda on January 29, 2026

In Part 4, we’ll make our Notice block actually look and act like a notice. We’ll add some baseline CSS to style the block and then write frontend JavaScript in view.js to handle dismissing the notice when users click that close button we added in Part 3.

In Part 3 of the series, we set up the Notice block to allow inner blocks, which allows us to add other blocks inside of our block. We also added Inspector Controls for the custom attribute: isDismissible along with a button that a user could use to hide the notice if we set isDismissible to true.

Our next step is to add some styling to make things look nice out of the box and make sure the dismiss button actually does something on the frontend.

Let’s dive in!

Styling the Notice block

Our goal now is to add some default styles to the block so it looks good out of the box and has some sensible defaults for things that might appear inside it. The key here is to not make the styles overly specific so that the inner blocks can still be styled as needed.

This is an important design pattern when you’re building a composable UI where users can put the various pieces (blocks) in various configurations that aren’t always the same. Not every notice will have the exact same text or blocks inside of it, so we need to make sure the styles are set up to accommodate this.

This principle of composability isn’t unique to WordPress or building pages with an editor of some kind. This is a fundamental concept for writing well-structured CSS for the web. You write styles and use selectors that are only as specific as they need to be. Then you apply more specific styles for overrides.

To begin, open up style.scss in the block folder and make sure the npm start task is running (npm run start). Right now, it just has a comment and some commented out CSS. Let’s begin by removing the extra comment and uncommenting the selector .wp-block-lwpd-notice:

src/blocks/notice/style.scss
.wp-block-lwpd-notice {
  // Styles will go here
}
SCSS

This class here was included in the generated file and is based on the block’s configuration. The class name is formatted like this:

.wp-block-{namespace}-{blockName}

By default, a block will have a block class name that is applied to the element that receives the block props from useBlockProps, which is almost always the element that wraps the rest of the block’s output.

Next we’ll add some CSS rules:

src/blocks/notice/style.scss
.wp-block-lwpd-notice {
	background-color: hsl(0deg 0% 93.73%);
	border: 1px solid hsl(0 0% 85%);
	color: hsl(0deg 0% 3.92%);
	font-size: 1.25rem;
	padding: 1rem;
	position: relative;
}
SCSS

We’ll add colors, a default font size for the whole container, relative positioning, and some padding for the container. If the start task was running when you saved the file, the changes will show up when you refresh the page. Here’s what this looks like in a default site using the twentytwentyfive theme:

Screenshot of the notice block on the site frontend with the newly applied styles.

If you’re familiar with building block themes, you might wonder: should I be using CSS variables for the block style values? The answer depends on the context in which you’re building the block. Are you building this block for a single site where you’re setting everything up and choosing the theme? Or are you writing this block to be distributed widely as a plugin?

If you’re building a block that will be distributed widely to sites that are using any theme, you won’t know exactly what CSS variables are in use. Most themes tend to disable default options and may have any number of CSS variables, so you can’t easily assume a certain variable will be available or what its value might be.

On the other hand, if you’re building a custom block for a site build and you’re also setting up and designing the theme then you should absolutely be using presets you define in theme.json instead of hardcoding the values if those presets are available. There are a number of benefits to this approach, but the biggest ones are visual consistency and easier maintenance. If you change the values of those CSS variables, they’ll update everywhere they’re used automatically.

Next, we’ll want to add some sensible button styles that ensure the button looks like it goes with the rest of the site’s styles. This is a tough thing to get exactly right when you’re building a plugin that could be used by any theme, so our goal is to do something minimal that will work for the majority of users and allow the theme’s button styles to apply as appropriate.

Additionally, we’ll need to update the initial class so that we can add extra padding on the right side (inline-end) that equals the size of the dismiss button. This allows us to position it in the top right corner in a way that it will never overlap with any of the inner blocks.

Finally, we’ll update the class name of the button to wp-block-lwpd-notice__dismiss for better consistency.

Note: Some themes like twentytwentyfive don’t actually set box-sizing globally1. If not, you should probably set box-sizing: border-box to the notice block so size and spacing properties will work how you expect.

src/blocks/notice/style.scss
.wp-block-lwpd-notice {
	--button-icon-size: 1.5rem;
	--button-padding: 0.5rem;
  
	background-color: hsl(0deg 0% 93.73%);
	border: 1px solid hsl(0 0% 85%);
	box-sizing: border-box; // Remove this if your plugin or theme already sets it.
	color: hsl(0deg 0% 3.92%);
	font-size: 1.25rem;
	padding: 1rem;
	padding-inline-end: calc(var(--button-icon-size) + var(--button-padding) * 2);
	position: relative;

	&__dismiss {
		background-color: transparent;
		border: none;
		box-shadow: none;
		color: currentColor;
		cursor: pointer;
		display: inline-flex;
		padding: var(--button-padding);
		position: absolute;
		right: 0;
		top: 0;
		
		
		svg {
			height: var(--button-icon-size);
			pointer-events: none;
			width: var(--button-icon-size);
		}
	}
}
SCSS

Let’s break down what’s going on these styles:

  • We use the & to build the selector. & is a placeholder for the selector above it (in this case: .wp-block-lwpd-notice). The resulting class is: wp-block-lwpd__dismiss. This selector is a single class and not overly specific.
  • We remove the background-color, border, and box-shadow.
    • By default, the browser’s user agent styles2 will typically set these properties on a button. We just want our button to show the icon without any of that for now.
  • Color is set to currentColor which is similar to setting to “inherit”.
    • I typically use this instead of inherit because you use currentColor with CSS color functions like color-mix and it provides more flexibility.
  • The svg icon inside the button is set display block, given an explicit size, and has pointer-events turned off.
    • pointer-events: none ensures that click events on the button work as expected.3
  • We add padding to ensure it’s at least 2rems (32px) square.
    • You typically want to make an interactive button at least this size if not slightly larger. It’s not always possible, but if it’s too small it can be really hard to click on, especially for people with motor skill issues.
  • cursor: pointer is added to ensure the button looks clickable if you mouse over it.
  • We use local CSS variables on the block’s top level class to calculate the button’s size (icon size + padding). We then use this value to set the padding on the top and right of the block.

Why go through the trouble of adding the CSS variables, you ask? You could arguably just hard code those values. In a smaller set of styles, maybe that’s just fine. However, if there’s ever a scenario where someone may want to control those values in the editor, using the variables would make that much simpler. Additionally, if we need to change the sizes at any point, we can just change them in one place and everything works as expected. If it’s easy and reasonable to do up front, it’s often worth doing while you’re building the thing (vs trying to retrofit it months/years later).

You may also want to add specific focus styles to add an outline to the button when someone focuses it with their keyboard. Block themes have baseline styles for this out of the box, so you don’t always need to add these yourself. But like all things, you should test this yourself and make sure the element’s focused state is perceptible. That is to say: if someone is focusing the button, there should be a clear indictor of that4.

Here’s how the block should look at this point if you’re following along:

Screenshot of the frontend showing the notice block after the new styles and markup changes are applied.
The notice block is showing with the dismiss button and the other styles we added.

Setting up interactivity for the dismiss button

Now the dismiss button is outputting on the page but it still doesn’t do anything. Now we’ll need to add some JavaScript to output along with our block to handle this. We’ll walk through a simple example of how we can hide the notice by clicking that button.

In Part 1 we went over the generate block files and how view.js is a file that loads only on the frontend and when the block is on the page. This is made possible by the “viewScript” key in block.json that points to “file:./view.js”.

There are a few things that we’ll need to do this properly:

  1. A way to tell the browser that the notice was hidden that persists across reloads.
  2. A way to uniquely identify multiple notices on the same page.

For #1, we’ll use window.localStorage and for #2, we can use an HTML ID for the block. Since we enabled anchor support, we can already type one in now. With that in mind, we can use a single event handler to watch for clicks on any notice block dismiss buttons and then store which one was dismissed in local storage.

src/blocks/notice/view.js
( function () {
	const { localStorage } = window;
	const noticeBlocks = document.querySelectorAll(
		'.wp-block-lwpd-notice[data-dismissible]'
	);

	// If no dismissible notice blocks, stop here.
	if ( ! noticeBlocks.length ) {
		return;
	}

	// Check all dismissible notice blocks to see if they should be visible or not.
	noticeBlocks.forEach( ( notice ) => {
		const storage = localStorage.getItem(
			`lwpd-notice-block-${ notice.id }-dismissed`,
			1
		);

		if ( storage ) {
			notice.remove();
		} else {
			notice.classList.add( 'is-visible' );
		}
	} );

	// Listen for all clicks on elements that match the selectors in .closest().
	document.addEventListener( 'click', function ( e ) {
		const noticeBlockDismiss = e.target.closest(
			'.wp-block-lwpd-notice__dismiss'
		);

		if ( ! noticeBlockDismiss ) {
			return;
		}

		// Get the block element.
		const noticeBlock = e.target.closest( '.wp-block-lwpd-notice' );

		// Check if the noticeBlock has an ID first.
		if ( noticeBlock?.id ) {
			localStorage.setItem(
				`lwpd-notice-block-${ noticeBlock.id }-dismissed`,
				1
			);

			// Remove the element from the DOM.
			noticeBlock.remove();
		}
	} );
} )();

As a general best practice, I recommend adding an Immediately Invoked Function Express (or IIFE) around your code. This ensures that everything you write remains in its own scope and isn’t exposed to the browser when view.js is loaded.

Here’s a breakdown of what the above code does:

  1. We look for any dismissible notice blocks that have an ID, then loop through them to see if they should be visible or not.
    • The is-visible class is added to show dismissible notices that haven’t been dismissed. Doing it this way prevents a flash on page load.
  2. We use event delegation to create a single event listener that will catch every instance of the dismiss button on the page. This is much better for performance (and easier to maintain) than doing a loop and setting a click handler for each one manually.
    • The closest() method makes all of this possible and easy to do. We can ask the handler if the thing we clicked is close to the selector. This allows us to not only do a check if a specific element was clicked, but we can also see if a user clicked inside a particular element.
  3. If the notice block has an ID, we set a local storage key that includes the block name and the ID and set the value to “1”. Then we remove the block from the DOM.

From here, we’ll need to add a little bit more to our stylesheet to make the is-visible class work:

src/blocks/notice/style.scss
.wp-block-lwpd-notice {
	--button-icon-size: 1.5rem;
	--button-padding: 0.5rem;
  
	background-color: hsl(0deg 0% 93.73%);
	border: 1px solid hsl(0 0% 85%);
	box-sizing: border-box;
	color: hsl(0deg 0% 3.92%);
	font-size: 1.25rem;
	padding: 1rem;
	padding-inline-end: calc(var(--button-icon-size) + var(--button-padding) * 2);
	position: relative;

	&[data-dismissible] {
		display: none;

		&.is-visible {
			display: block;
		}
	}

	&__dismiss {
		background-color: transparent;
		border: none;
		box-shadow: none;
		color: currentColor;
		cursor: pointer;
		display: inline-flex;
		padding: var(--button-padding);
		position: absolute;
		right: 0;
		top: 0;
		
		
		svg {
			height: var(--button-icon-size);
			pointer-events: none;
			width: var(--button-icon-size);
		}
	}
}
SCSS

Once you save all of these changes, your Notice block will now properly support dismissal! Test it out and add another notice block without an ID.

There’s one problem though: if we have the block set to be dismissible, it won’t show up in the editor! The logic to add the visibility all comes from view.js, which is only loading on the frontend! The simple fix for this is to add styles that are only in the editor to ensure the block is always visible in the editor.

We previously removed that editor.scss, but we can easily add it back to support this use case! To do so, you’ll need to go back to block.json and add the “editorStyle” key that points to index.css, recreate editor.scss, then import it into edit.js. We can then add a simple style that ensures the block is always visible even if it has data-dismissible.

Why index.css and not editor.scss? Because the built css in the build folder is in index.css. SCSS files are used to create the built file.

src/blocks/notice/block.json
{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "lwpd/notice",
	"version": "0.1.0",
	"title": "Notice",
	"category": "widgets",
	"icon": "smiley",
	"description": "Example block scaffolded with Create Block tool.",
	"example": {},
	"attributes": {
		"isDismissible": {
			"type": "boolean",
			"default": false
		}
	},
	"supports": {
		"align": [ "wide", "full" ],
		"anchor": true,
		"color": {
			"background": true,
			"text": true,
			"link": true
		},
		"html": false,
		"layout": true,
		"spacing": {
			"margin": true,
			"padding": true,
			"blockGap": true,
			"__experimentalDefaultControls": {
				"blockGap": true,
				"margin": false,
				"padding": false
			}
		},
		"typography": {
			"fontSize": true,
			"lineHeight": true,
			"__experimentalFontFamily": true,
			"__experimentalFontStyle": true,
			"__experimentalFontWeight": true,
			"__experimentalDefaultControls": {
				"fontSize": true,
				"lineHeight": true
			}
		}
	},
	"textdomain": "notice",
	"editorScript": "file:./index.js",
	"editorStyle": "file:./index.css",
	"style": "file:./style-index.css",
	"viewScript": "file:./view.js"
}
src/blocks/notice/editor.scss
.wp-block-lwpd-notice {
  &[data-dismissible] {
		display: block;
  }
}
src/blocks/notice/edit.js
import { __ } from '@wordpress/i18n';
import {
	useBlockProps,
	useInnerBlocksProps,
	InspectorControls,
} from '@wordpress/block-editor';
import { PanelBody, ToggleControl, Icon } from '@wordpress/components';
import { close } from '@wordpress/icons';
import { useId } from '@wordpress/element';

import './editor.scss';

const TEMPLATE = [
	[
		'core/heading', // Block name
		{ content: __( 'Notice title', 'lwpd' ) }, // Block attributes
	],
	[
		'core/paragraph', // Block name
		{
			content: __( 'Add notice content…', 'lwpd' ), // Block Attributes
		},
	],
];

export default function Edit( { attributes, setAttributes } ) {
	const { isDismissible, anchor } = attributes;
	const blockProps = useBlockProps( {
		'data-dismissible': isDismissible || undefined,
	} );
	const innerBlocksProps = useInnerBlocksProps( {
	  className: 'wp-block-lwpd-notice__children'
	}, {
		template: TEMPLATE,
	} );

	const fallbackId = 'lwpd-notice' + useId();

	return (
		<>
			<div { ...blockProps }>
				{ isDismissible && (
					<button
						className="wp-block-lwpd-notice__dismiss"
						type="button"
						aria-label={ __( 'Dismiss Notice', 'lwpd' ) }
					>
						<Icon icon={ close } size="24" />
					</button>
				) }
				<div { ...innerBlocksProps } />
			</div>
			<InspectorControls>
				<PanelBody title={ __( 'Settings', 'lwpd' ) }>
					<ToggleControl
						label={ __( 'Dismissible', 'lwpd' ) }
						help={
							isDismissible
								? __( 'Users can dismiss this notice.', 'lwpd' )
								: __( 'Notice will always be visible.', 'lwpd' )
						}
						checked={ isDismissible }
						onChange={ ( value ) => {
							const updates = { isDismissible: value };

							if ( value && ! anchor ) {
								updates.anchor = fallbackId;
							}

							setAttributes( updates );
						} }
					/>
				</PanelBody>
			</InspectorControls>
		</>
	);
}

Going the extra mile

If we really wanted to make a nice user experience (UX) we should only output the dismiss button if there’s actually an ID, otherwise the button won’t work. We can also generate an ID for someone if they haven’t inserted one but then enable the option, which makes it about as easy as it gets for our users.

To do this, we’ll just need to add a bit of logic to our edit.js file:

src/blocks/notice/edit.js
import { __ } from '@wordpress/i18n';
import {
	useBlockProps,
	useInnerBlocksProps,
	InspectorControls,
} from '@wordpress/block-editor';
import { PanelBody, ToggleControl, Icon } from '@wordpress/components';
import { close } from '@wordpress/icons';
import { useId } from '@wordpress/element';

const TEMPLATE = [
	[
		'core/heading', // Block name
		{ content: __( 'Notice title', 'lwpd' ) }, // Block attributes
	],
	[
		'core/paragraph', // Block name
		{
			content: __( 'Add notice content…', 'lwpd' ), // Block Attributes
		},
	],
];

export default function Edit( { attributes, setAttributes } ) {
	const { isDismissible, anchor } = attributes;
	const blockProps = useBlockProps( {
		'data-dismissible': isDismissible || undefined,
	} );
	const innerBlocksProps = useInnerBlocksProps( {
	  className: 'wp-block-lwpd-notice__children'
	}, {
		template: TEMPLATE,
	} );

	const fallbackId = 'lwpd-notice' + useId();

	return (
		<>
			<div { ...blockProps }>
				{ isDismissible && (
					<button
						className="wp-block-lwpd-notice__dismiss"
						type="button"
						aria-label={ __( 'Dismiss Notice', 'lwpd' ) }
					>
						<Icon icon={ close } size="24" />
					</button>
				) }
				<div { ...innerBlocksProps } />
			</div>
			<InspectorControls>
				<PanelBody title={ __( 'Settings', 'lwpd' ) }>
					<ToggleControl
						label={ __( 'Dismissible', 'lwpd' ) }
						help={
							isDismissible
								? __( 'Users can dismiss this notice.', 'lwpd' )
								: __( 'Notice will always be visible.', 'lwpd' )
						}
						checked={ isDismissible }
						onChange={ ( value ) => {
							const updates = { isDismissible: value };

							if ( value && ! anchor ) {
								updates.anchor = fallbackId;
							}

							setAttributes( updates );
						} }
					/>
				</PanelBody>
			</InspectorControls>
		</>
	);
}

In the above changes, we can create a fallbackId value using the useId hook from React (imported from @wordpress/element) which will generate a unique fallback for us. We then update the onChange handler to set the anchor if there isn’t one set and someone enables isDismissible.

Next Steps

At this point, we have a pretty solid bit of functionality. In Part 5, we’ll take it a step further and create some different styles for our block that are passed on the type of notice it is (success, warning, alert, etc).

Further Reading

  1. It’s 2026, everyone should be setting box-sizing to border-box by default since virtually no one expects things like padding and border to change the width they set. If you really want context-box (the default) as the value, you can intentionally set it that way. ↩︎
  2. In CSS, “User Agent” refers to the browser or any other thing that is rendering the web page for a user. If you inspect most elements, open the Style tab in dev tools, then scroll to the bottom, you’ll typically see styles that come from the “user agent stylesheet”. Each user agent stylesheet is slightly different, but many set similar CSS rules. ↩︎
  3. If the user clicks on the SVG in the button, the click event target will be considered the svg tag itself, not the button. Using pointer-events: none prevents this. ↩︎
  4. See WCAG 2.1 success criterion 2.4.7 ↩︎


Leave a Reply

Your email address will not be published. Required fields are marked *