1

I'm working on a custom block that renders a series of DIVs differently depending on the device on which it is displayed. On desktop, the DIVs need to be displayed horizontally with a right margin of x pixels, where x can be dynamically altered via a block inspector control. On mobile, the DIVs need to be displayed vertically with a bottom margin of x pixels, where x is controlled by the same setting.

One can use the style attribute to add inline dynamic styles to a block in the edit function, like this:

<div className="item" style={(window.innerWidth < 768) ? { marginBottom: gap } : { marginRight: gap }} key={index}>

where gap is a dynamic value set via the block inspector.

But this cannot be used in a dynamic block rendered via PHP in the frontend.

The ideal solution would be to embed an inline CSS media query for this (a static one cannot be used because of the gap value), but I don't know how to attach one to a block on both the editor and the render_callback function for the frontend.

Any help will be greatly appreciated.

1 Answer 1

2

If we stick to your exact example, I would define the value as a custom property in an inline style:

<div class="item" style="--my-gap: <?php echo esc_attr( $attributes['gap'] ); ?>;">

Then in CSS use a media query to use the property as the appropriate margin:

.item {
    margin-bottom: var(--my-gap);
}

@media ( min-width: 768px ) {
    .item {
        margin-bottom: 0;
        margin-right: var(--my-gap);
    }
}

But if you're trying to lay out a grid, or set of columns and rows, I would suggest using something modern like flexbox or grid and using the gap property.

If display: flexbox and gap can work to get the result you want, then you could look at supporting blockGap in your block. In WordPress 6.2 this is still experimental, but it might be finalised in 6.3. To add support for blockGap in your custom block add it to supports in your block.json file:

"supports": {
    "spacing": {
        "blockGap": true
    }
}

Then declare your block's layout as flex:

"supports": {
    "__experimentalLayout": {
        "allowEditing": false,
        "default": {
            "type": "flex"
        }
    }
}

In a future version of WordPress __experimentalLayout will probably become layout.

This will enable the core "Block spacing" control for your block, which will let users adjust the spacing using the spacing presets/configuration defined by their theme. The selected value will be automatically output as the gap CSS property on the block's main element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.