TIL how to add custom styles in WP Blocks
POSTED ON:
Justin Tadlock of WPTavern recreates a theme in block patterns.
Tutorial:
https://wptavern.com/recreating-onia-building-brushstroke-backgrounds-with-wordpress-blocks
One of my favorite design elements of the theme was its use of an SVG to create a brushstroke behind the intro heading:
The theme used an old-school method of wrapping a
<span>
element inside an<h1>
. This applies the brush background to the last few words of the text. However, that implementation is problematic with smaller devices, not keeping up with the natural flow of text-breaks as the screen changes. There was also no way for users to control the color of the brushstroke or text.
Justin actually creates a new Block Property called brushstroke
, where he can add it to the element.
To create the brushstroke background for Heading blocks, I added the following code to my theme,
Then, I downloaded the brush-stroke-big.svg file from the WordPress News repo and added it to an /assets/svg folder in my theme.
<?php
// functions.php
add_action( 'init', 'tavern_register_block_styles' );
function tavern_register_block_styles() {
register_block_style( 'core/heading', [
'name' => 'brush',
'label' => __( 'Brush', 'tavern' )
] );
}
// style.css
/* Cancel out WP's padding on headings with backgrounds. */
:is( h1, h2, h3, h4, h5, h6 ).is-style-brush.has-background {
padding: 0;
}
/* Add default background to headings. Clip it to the text. */
:where( h1, h2, h3, h4, h5, h6 ).is-style-brush {
position: relative;
z-index: 1;
background-color: #b5b5b5;
background-clip: text !important;
-webkit-background-clip: text !important;
}
/* Adds the brushstroke to ::before. Using ::after can conflict with editor. */
:where( h1, h2, h3, h4, h5, h6 ).is-style-brush::before {
content: "";
position: absolute;
z-index: -1;
bottom: -1rem;
left: -1rem;
height: calc( 1.25em + 1rem );
width: 100%;
background-color: inherit;
-webkit-mask-image: url('assets/svg/brush-stroke-big.svg');
mask-image: url('assets/svg/brush-stroke-big.svg');
-webkit-mask-position: left bottom;
mask-position: left bottom;
-webkit-mask-repeat: no-repeat;
mask-repeat: no-repeat;
-webkit-mask-size: 100% 100%;
mask-size: 100% 100%;
}
Related TILs
Tagged: wordpress