Custom Block Development Part-2: How to add styling in the block

In this article, we are going to take a look at how we can CSS and basic edit functionality to our WordPress custom block. This article is the next part of our previous article, if you haven’t read and have that code then please read it and then continue else you might not understand what we are doing here.

Objective

First let’s take a look at what we are building today, in the previous article we have built a basic “Hello World!” custom block. Now we are going to make it look like an actual useful block, for that we will add some more content, some CSS and we also take a look at how we can add a separate stylesheet for our block.

In this custom block, we will have a heading at the top, a paragraph, and a button with a link. You can see the block preview in the image above.

Now let’s take a look at how we can actually achieve it.

Note: One thing I recommend you to do for the custom block is before coding for a block in JS first create that block in simple HTML and CSS and after making it use that code as a reference, else editing things directly while coding will be a lot tougher and you won’t even get the syntax to autocomplete for HTML and CSS. While coding in ES 5 it won’t be reusable that much but when you use ES Next, you can use most of your HTML and CSS.

Step 1: Add Elements

The first thing that we are going to do is to add some more elements for our blog, to add elements we will return elements in the return statements of our  edit: function()and save: function().

First, we will add a divelement.

el('div', {} ,
                    
)

and then inside that div element, we will add a h2element.

el(
'h2', {},"HEADING"
),

In the same way, we will add a paragraph and an anchor in the div.

el(
    'p', {},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
),
el(
    'a', {} , "Click Me"
),

We will do the same thing with our edit and save’s return statement and the final code will look as shown below.

edit: function() {
    return( 
        el('div', } ,
            el(
                'h2', {},"HEADING"
            ),
            el(
                'p', {},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
            ),
            el(
                'a', {} , "Click Me"
            ),
        )
    )
},

//Block Save Function
save: function() {
    return( 
        el('div', {} ,
            el(
                'h2', {},"HEADING"
            ),
            el(
                'p', {},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
            ),
            el(
                'a', {} , "Click Me"
            ),
        )
    )
},

Step 2: Add Link

Now let’s add a link in our anchor tag, for now, we are hardcoding the link in our element later we will see how to give the option to edit it in the front end. To add the link in our atag in the element second parameter we need to pass href as an object. like shown below:

el('a', {href:'https://example.com'} , "Click Me")

Step 3: Add Styling

Now let’s take a look at how we can add styling to our custom block. For now, we will use inline styling later we will see how we can add a separate style sheet for our block.

To add styling we will declare styling as an object on top of our article, we can directly use them in element inline like:

el('h2', {style: {background: '#000'},"HEADING", "Heading"}

But since we need these styles for both our editand savefunction, so it will be wiser to write them in variable objects and reuse the same in both functions.

So for styling, we will make three separate styling objects for styling three separate things. First, we will make an object to style our div:

var blockStyle = {
    background: '#fff',
    padding: '30px',
    'text-align': 'center',
    'border-radius': '20px' 
}

One thing you may have noticed is that the above code is not the same as normal CSS, that is because we are not coding in CSS but in objects, and React is converting that object into CSS. We can use all the properties of CSS but we need to focus on a couple of things. First, we don’t use semicolons ;instead, we end line with a comma in an object, and second, since we are coding as an object if our CSS property name (in object case that would be object key) has a hyphen - then we need to wrap that key in single quotes ''.

In the same way, as above we will create a styling object variable for our paragraph and anchor tag to make it look like a button.

var paraStyle = {
    margin: '20px'
}
var buttonStyle = {
    background: '#000',
    border: '0px',
    'border-radius': '5px',
    padding: '12px 35px',
    color: '#fff',
    'font-family': 'sans-serif',
    'text-decoration': 'none',
    'margin': '10px'
}

Now we need to use these styling objects in our save and edit functions. To do that inside element tag next to element type(or second parameter) we will add styling object {style:objectVariableName}.  The complete code with styling will be like the given below:

( function( blocks, element) {
    var el = element.createElement;
    var blockStyle = {
        background: '#fff',
        padding: '30px',
        'text-align': 'center',
        'border-radius': '20px' 
    }
    var paraStyle = {
        margin: '20px'
    }
    var buttonStyle = {
        background: '#000',
        border: '0px',
        'border-radius': '5px',
        padding: '12px 35px',
        color: '#fff',
        'font-family': 'sans-serif',
        'text-decoration': 'none',
        'margin': '10px'
    }


    // Registering A Block
    blocks.registerBlockType('wpt/wpt-block', {
        title: 'WPT Custom Block',
        category: 'common',
        icon: 'superhero',
        description: 'First Hello World Block',
        keyword: ['test', 'searchme'],

        // Block Edit Function
        edit: function() {
            return( 
                el('div', {style: blockStyle} ,
                    el(
                        'h2', {},"HEADING"
                    ),
                    el(
                        'p', {style:paraStyle},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
                    ),
                    el(
                        'a', {style: buttonStyle, href:'https://example.com'} , "Click Me"
                    ),
                )
            )
        },

        //Block Save Function
        save: function() {
            return( 
                el('div', {style: blockStyle} ,
                    el(
                        'h2', {},"HEADING"
                    ),
                    el(
                        'p', {style:paraStyle},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
                    ),
                    el(
                        'a', {style: buttonStyle, href:'https://example.com'} , "Click Me"
                    ),
                )
            )
        },
    } );
})( window.wp.blocks, window.wp.element);

After that save the file and load the custom block into your Gutenberg Editor. You’ll see your newly coded block.

Note: One issue I have noticed with my setup is the Block looks a bit different in the Block Editor than the published page, maybe because of my theme or some bug. The main difference was in the heading, maybe because of my theme’s default setting. So always confirm your block layout in both editor and published page.

You can fix it with some extra CSS in your code I have left it as it is for demonstration purposes, you can see the difference in the image above. But most probably this may not occur for you at all.

Step 4: Add Style Sheet

Now let’s take a look at how we can add a separate style sheet for our block. First, create a CSS file in your plugin folder, you can save it anywhere I am creating it in the wpt-block folder where your JS file exists. After adding the file add your CSS to it.

Now we need to load that CSS style sheet on our site, we can load it from our plugin’s main PHP file. To load the style sheet we need to add it, we will use wp_register_style();function to add it. The code will look like this:

// Add block style.
wp_register_style(
    'style',
    plugins_url( 'wpt-block/style.css', __FILE__ ),
    []
);

After that we need to register that script so WordPress will load it, we can register it in the same way as we have registered the block script file. We will add 'style' => 'style'inside our register_block_type();function like the example below:

// Register block script and style.
register_block_type( 'wpt/wpt-block', [
    'style' => 'style',
    'editor_script' => 'wpt-block',
] );

The next step is to add classes to block elements. To add classes we will replace the key-value pair object of our element where previously we have added style object, no we will replace it with className:'your_class_name'.

Complete Custom Block Code

With that our coding part for this article is now complete and here is how the complete code looks now.

File: wpt-blocks.js

( function( blocks, element) {
    var el = element.createElement;


    // Registering A Block
    blocks.registerBlockType('wpt/wpt-block', {
        title: 'WPT Custom Block',
        category: 'common',
        icon: 'superhero',
        description: 'First Hello World Block',
        keyword: ['test', 'searchme'],

        // Block Edit Function
        edit: function() {
            return( 
                el('div', {className:'wpt-heading'} ,
                    el(
                        'h2', {},"HEADING"
                    ),
                    el(
                        'p', {className:'wpt-para'},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
                    ),
                    el(
                        'a', {className:'wpt-button', href:'https://example.com'} , "Click Me"
                    ),
                )
            )
        },

        //Block Save Function
        save: function() {
            return( 
                el('div', {className:'wpt-heading'} ,
                    el(
                        'h2', {},"HEADING"
                    ),
                    el(
                        'p', {className:'wpt-para'},"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
                    ),
                    el(
                        'a', {className:'wpt-button', href:'https://example.com'} , "Click Me"
                    ),
                )
            )
        },
    } );
})( window.wp.blocks, window.wp.element);

File: plugin.php

<?php
/** 
 * Plugin Name: WPT Custom Blocks
 * Plugin URI: https://github.com/ 
 *  Description: A Custom block created for learnirng by WebProTime team. 
 *  Version: 1.0.0 
 *  Author: WebProTime 
 * 
 */

function wpt_register_blocks() {

    // Check if Gutenberg is active.
    if ( ! function_exists( 'register_block_type' ) ) {
        return;
    }

    // Add block script.
    wp_register_script(
        'wpt-block', 
        plugins_url( 'wpt-block/wpt-block.js', __FILE__ ), 
        ['wp-blocks', 'wp-editor']
    );

    // Add block style.
    wp_register_style(
        'style',
        plugins_url( 'wpt-block/style.css', __FILE__ ),
        []
    );


    // Register block script and style.
    register_block_type( 'wpt/wpt-block', [
        'style' => 'style',
        'editor_script' => 'wpt-block',
    ] );
}

add_action( 'init', 'wpt_register_blocks' );

File: style.css

.wpt-heading {
    background: rgb(155,221,235);
    background: radial-gradient(circle, rgba(155,221,235,1) 0%, rgba(0,207,249,1) 100%);
    padding: 30px;
    text-align: center;
    border-radius: 20px;
}
.wpt-para {
    margin: 20px;
}
.wpt-button {
    text-decoration: none;
    background: #000;
    border: 0px;
    border-radius: 5px;
    padding: 12px 35px;
    color: #ffffff !important;
    font-family: sans-serif;
}
.wpt-button:hover {
    text-decoration: none;
    background: rgb(255, 255, 255);
    color: #000 !important;
}

After completing the above code make sure to save all the files and load the custom block in the editor you will see it like the image below.

custom block

Conclusion

Now you have learned how you can add style into your custom block via a separate style sheet And inline CSS too. Now you should be able to create stylish-looking static custom blocks. In the upcoming articles, we will see how we can make our custom block customizable so end-user can edit the.

You can get the complete source code used in this article and in the complete series on my Github repo.

If you have any doubts, questions, suggestions or anything make sure to comment them down below.

Have questions or confused about something WordPress Related? Join Our Discord Server & ask a Question

Leave a Comment

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

Scroll to Top
Scroll to Top