Customizing Gutenberg blocks with block styles

Block styles are a simple way to get started with Gutenberg development: With a few lines of CSS, you can build something that feels like a whole new custom block.

A few years ago, Matt Mullenweg urged us all to “Learn JavaScript Deeply.” Becoming more familiar and comfortable with JavaScript is increasingly important for those of us who build the web. In the world of WordPress, projects like Gutenberg have begun taking a major step into a JavaScript-powered future.

For designers and developers who are still getting used to these new languages and workflows, creating and customizing Gutenberg blocks can be somewhat intimidating. There are excellent toolkits like Create GutenBlock to help you get started, but even using those, building a block requires quite a bit of JavaScript familiarity. You also have to make sure you’ve got the right version of Node, learn some terminal commands, install some dependencies, etc. There’s quite a bit of up-front work necessary before you can jump in and start actually building something.

Despite these hurdles, we’ve seen an inspiring number of new block plugins surface lately: CoBlocks, and Atomic Blocks are great examples. They each add a variety of rich blocks, and truly enhance the site-building experience.

There’s a much simpler way to start customizing Gutenberg blocks though, and it’s something we haven’t seen utilized much at this point: block styles. They take only a few minutes to pick up, and mostly just require you to know CSS.

You’ve likely noticed block styles while using Gutenberg. The Quote, Pullquote, Separator, Table, and Button blocks ship with some alternate styles by default.

Block styles are an excellent but relatively unused area of Gutenberg customization. They’re a simple way to get started with Gutenberg development: With a few lines of CSS, you can build something that feels like a whole new custom block. Also, since they’re reusable across multiple sites, block styles help pave the way for a more flexible system of components that make up a site’s theme.

Technically, block styles are very simple. They’re composed of two things:

  • A few lines of JavaScript to declare the block variation and give it a custom class name.
  • CSS styles to fine-tune the appearance.

That’s it. A block style is a custom block class, with some styles applied.

Implementation

A block style can be implemented anywhere you can enqueue a little JavaScript and some CSS. For this example, I’m going to focus on implementing a custom block style via a plugin. One of the benefits of using a plugin is that it’s not tied to the user’s theme. This allows your block style to be used across any site, running any theme — as if you had built an entirely new custom block.

The first step to implementing block styles is to create a few files:

  • index.php to set up the plugin and enqueue the other files
  • blocks.js to declare the block style
  • style.css to house the actual styles

index.php

By default, index.php just needs to initialize the plugin with a DocBloc, and enqueue the JavaScript and CSS files:

<?php
/**
* Plugin Name: Block Styles
*/

/**
* Enqueue JavaScript
*/
function block_styles_enqueue_javascript() {
wp_enqueue_script( 'block-styles-script',
plugins_url( 'block.js', FILE ),
array( 'wp-blocks')
);
}
add_action( 'enqueue_block_editor_assets', 'block_styles_enqueue_javascript' );

/**
* Enqueue Stylesheet
*/
function block_styles_enqueue_stylesheet() {
wp_enqueue_style( 'block-styles-stylesheet',
plugins_url( 'style.css', FILE )
);
}
add_action( 'enqueue_block_assets', 'block_styles_enqueue_stylesheet' );

block.js

The JavaScript file is where you’ll let Gutenberg know you’re declaring a new Block Style. That requires a few lines of code:

wp.blocks.registerBlockStyle( 'core/paragraph', {
name: 'blue-paragraph',
label: 'Blue Paragraph'
} );

The first line tells Gutenberg which existing block to start with. In this example, we are going to create a block style for the Paragraph block. Any existing block can inherit a block style*, so if you were to target a different block, you’d change core/paragraph to the name of a different block. Technically, these names are found in the Gutenberg block source code, but they’re usually easily guessable. For example: core/cover, core/separator, etc.

The name: field on the second line here creates the custom class that’ll be assigned to the block. In this case, I’m calling it a blue-paragraph, but it can be anything you’d like. Since this will be used for a CSS class, be sure not to use any spaces.

The final field corresponds to the label for your block style. This will be shown in the interface when someone opens the “Block Styles” panel.

style.css

The last file is pretty straightforward. Use the custom class name you created in block.js (along with a is-style- prefix), and insert your styles inside:

.is-style-blue-paragraph {
// Custom CSS styles go here.
}

Your styles here will build off of the default block styles, and will be loaded in before a theme’s editor styles. So be sure to keep your selectors specific enough to override those potentially competing styles.

Block Styles Plugin Boilerplate

To help you get started, I’ve created a GitHub repository that you can clone and use to get started. It contains the three files detailed above, along with some light documentation.

https://github.com/Automattic/gutenberg-block-styles

Out of the box, the repository is a small plugin that adds a “Blue Paragraph” block style to the Paragraph block:

With a few small adjustments, it’s possible to change this into something drastically different. There’s another branch on that GitHub repository that includes a Music theme-style cover block variant:

I’ve included a third branch that adds a somewhat ridiculous animation to the text (or emoji) inside of a Cover block:

Both of these are accomplished by changing about a dozen lines of code in the repo. They took minutes to create, and work across any site that uses Gutenberg, regardless of the theme it’s using.

What will you create?

Block styles are ripe with possibility. I’d love to see a CSS Zen Garden-style plugin someday that showcases dozens of different ways to customize blocks through block styles.

In the meantime, have you built something cool using block styles? If so, I’d love to hear about it. Please share your explorations in the comments.


*Note: At the time of writing, blocks that accept InnerBlocks (like the Media & Text and Column blocks) have a bug which causes them to crash when custom styles are assigned. There’s an open issue on GitHub to address this.

* { box-sizing: border-box; } FTW

Paul Irish on HTML element widths being inclusive of padding at all times. That is to say if I define my box as 200 pixels wide then it should stay at a total of 200 pixels, no matter what I use for its padding value.

The money shot is as follows:

* { /* apply a natural box layout model to all elements */
	-moz-box-sizing: border-box;
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
}

Also, an interesting read on using * and its impact on performance.

You might get up in arms about the universal * selector. Apparently you’ve heard its slow. Firstly, it’s not. It is as fast as h1 as a selector. It can be slow when you specifically use it like .foo > *, so don’t do that. Aside from that, you are not allowed to care about the performance of * unless you concatenate all your javascript, have it at the bottom, minify your css and js, gzip all your assets, and losslessly compress all your images. If aren’t getting 90+ Page Speed scores, its way too early to be thinking about selector optimization.

As with most CSS, there’s no one-size-fits-all choice for this. At times it makes sense (it’s used on the WordPress.com Theme Showcase, selectively though) and at other times it doesn’t.

I like it, though.

Head over to Irish’s site to weigh in or drop a comment here with your thoughts.

The Webkit Web Inspector

For those that fancy doing web design and debugging on Webkit browsers, here is a recently announced round of improvements.

I personally shall appreciate the fact that color values are rendered as originally written —if desired—, which should make experimenting and copying from the browser to the original stylesheet much easier, by preserving the chosen code style. The style presentation and persisting changes add-ons are equally neat.

CSS Tip: Hiding Content with Clip

In our themes on WordPress.com we often hide text from screen display but still want it to remain for screen readers. Typical techniques like text-indent and absolute positioning work fine until you try to add RTL support to the theme. After adding RTL styles those techniques cause layout issues; most commonly a huge horizontal scrollbar in certain flavors of IE.

Here’s a technique I came across on Adaptive Themes (Professional Drupal themes and design services) that works really well for this situation.

.element-invisible {
  position: absolute !important;
  clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  clip: rect(1px, 1px, 1px, 1px);
}

In our testing it seems to work great across all our target browsers.

See the full post on the Adaptive Themes site: Using CSS clip as an Accessible Method of Hiding Content.

How To Reset & Rebuild WordPress Theme CSS & Define Your Layouts

Update: We’ve created a second edition of this article, with updated code samples and coverage of the latest theme development techniques. Check it out at How To Reset & Rebuild WordPress Theme CSS & Define Your Layouts. It’s part of The ThemeShaper WordPress Theme Tutorial: 2nd Edition.

CSS can be tricky. It can also be incredibly easy. I had a lot of help getting my head wrapped around CSS when I was first starting out and I take great pleasure in helping others the same way I was first helped: with solid code examples to learn from.

Here we’re going to layout a WordPress Theme CSS development arsenal for you:

  • A stylesheet that resets default CSS across all web browsers and makes a sane standard we can work from
  • Another stylesheet that rebuilds our typographical foundations in a smart way
  • A stylesheet just for WordPress classes (keeping the first two pure so we can use them for non-WordPress projects)
  • A series of 6 fluid stylesheets that will create ALL the common blog and website layouts you expect—and each one ready to adapt into a fixed width layout.

All the code we’ll talk about is open-source, under the GPL, and browse-able at the Your Theme Project Page. View the raw source for any one of these files and copy-paste at your leisure.

First things first, make a “style” directory in your Theme folder. That’s where we’ll be putting everything. Your CSS quiver, as it were. Ready to hit the target?

Reset CSS

Our Reset CSS is adapted from Eric Meyer’s famous Reset CSS with some minor, minor changes. Basically what it does is take all the typographical defaults of every browser and … obliterates them. You’re left with a squashy, gray mess.

It’s beautiful.

What this does is equalize the rendering of every browser, leaving you free to ignore countless individual quirks particular to each one.

Using it is simple. Add the following lines to your style.css, at the very top, immediately after the initial comments section.

/* Reset default browser styles */
@import url('styles/reset.css');

Reload, your page and check it what reset.css does in multiple browsers (if you can). It’s wonderfully gross, isn’t it?

Rebuild CSS

Our Rebuild CSS is my own personal invention adapted from an early version of the Blueprint CSS typography stylesheet and refined in the Thematic Project. What it does is swing back some vertical rhythm in our pages, but in a really smart way.

What I’ve tried to do with this iteration of my typography-rebuild CSS is combine the best of both worlds for web typography: using Pixels for font height, with relative line-height for the main declaration on the body element, and Ems for all subsequent vertical margins (like for paragraphs and lists).

What does this mean? It’s really easy to set your font height later—without doing any math work—and have all of your typographical elements follow suit with an appropriate vertical rhythm (the vertical space between type elements like paragraphs and lists).

Using rebuild.css is also really easy. Just add the following lines immediately after your reset.css import.

/* Rebuild default browser styles */
@import url('styles/rebuild.css');

The Basic WordPress Styles

There are some elements in WordPress that you’re just going to have to style every time. What I’ve done is taken those styles and put them in there own little corner called wp.css.

Right now, what we’ve got in there are styles for floating all the images—including handling captions and image galleries. And! preset styles for simple pull-quotes. All you need to do is add a class of left or right to the blockquote tag and you’re ready to roll.

Can you guess how we’re going to use wp.css?

/* Basic WordPress Styles */
@import url('styles/wp.css');

All The Layouts You’ll Ever Need

For your new theme, I’ve taken the rock-solid, indestructible layouts that shipped with the Sandbox Theme and adapted them for your new HTML structure. There are 6 in total. Each is a fluid layout (that stretches to fill the width of your browser window) but each one is easily adaptable to a fixed width layout.

Using anyone of these layouts is simple. Immediately after your basic WordPress styles import, import one of these layouts. Here’s how to import the 3 column layout, with the content in the center.

/* Import a basic layout */
@import url('styles/3c-b.css');

The simplest method of turning any one of these layouts into a fixed-width layout is to add a width and centering margin to the #wrapper div.

#wrapper {
  margin: 0 auto;
  width: 960px;
}

Bonus: Styling The Menu

If you’ve never taken an unordered list (that’s the smart markup generated by wp_page_menu) and styled it to look like a menu before it can seem kinda weird. As a bonus, here’s the CSS I use when I start out creating menus for WordPress Themes.

#access {
	margin: 0 0 1.5em 0;
	overflow: auto;
}
.skip-link {
	position:absolute;
        left:-9000px;
}
.menu ul {
	list-style: none;
	margin: 0;
}
.menu ul ul {
	display: none;
}
.menu li {
	display: inline;
}
.menu a {
	display: block;
	float: left;
}

It’s pretty simple but it’ll put you on sure footing. Good luck!

How To Create a WordPress Theme

This post concludes the WordPress Themes Tutorial series that shows you how to create a powerful WordPress Theme from scratch. Read it from the beginning and code yourself up something awesome.

  1. WordPress Theme Tutorial Introduction
  2. Theme Development Tools
  3. Creating a Theme HTML Structure
  4. Template and Directory Structure
  5. The Header Template
  6. The Index Template
  7. The Single Post, Post Attachment, & 404 Templates
  8. The Comments Template
  9. The Search Template & The Page Template
  10. The Archive, Author, Category & Tags Template
  11. The Sidebar Template
  12. Reset-Rebuild Theme CSS & Define Your Layouts

If you have any suggestions for posts that will fit in this series or complement what we’ve done so far I’d be glad to hear them. Let me know in the comments.