Conditional CSS in Bricks based on Post Meta

In the Bricks Facebook group a user asked:

Hi, how do you normally control margin, padding and font-size using dynamic data? I’m looking for the best workflow to accommodate these rather unusual scenarios.

This Pro tutorial covers two ways this can be done in Bricks.

  • Using style attribute and adding the CSS inline
  • Registering a blank custom stylesheet, enqueuing it, building the CSS string with property values from post meta, and using wp_add_inline_style() to push the CSS from the string into the enqueued stylesheet.

Sample Scenario

ACF Field group: Page Fields

When a specific Page is being edited:

Method 1: Using style attribute and adding the CSS inline

Add a style attribute for the element, say a Button like this:

font-size: {acf_button_font_size}rem; padding: {acf_button_vertical_padding}em {acf_button_horizontal_padding}em

Method 2: wp_add_inline_style() to a custom stylesheet

Select the Button element → STYLE → CSS → CSS classes: btn--lg

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php

add_action( 'wp_enqueue_scripts', 'bl_styles_method_20242801' );
function bl_styles_method_20242801() {
	if ( ! is_page( 'test-page-1' ) ) return;

	wp_register_style( 'custom-style', false );
	wp_enqueue_style( 'custom-style' );

	$font_size = get_field( 'button_font_size' );
	$vertical_padding = get_field( 'button_vertical_padding' );
	$horizontal_padding = get_field( 'button_horizontal_padding' );

	$css = "
		.btn--lg {
			font-size: {$font_size}rem;
			padding: {$vertical_padding}em {$horizontal_padding}em;
		}
	";

	wp_add_inline_style( 'custom-style', $css );
}

Replace

is_page( 'test-page-1' )

as appropriate.

This technique has also been covered in the Adding CSS based on a PHP boolean value in WordPress tutorial.