Skip to main content

Custom CSS Styles

Objective​

The goal is to enable users to write and apply custom CSS through a module's settings in the Advanced Tab. The implementation ensures that custom CSS styles override module default and modified settings styles.

This understanding will be put in practice in next tutorials.

Prerequisites​

This tutorial assumes that you have read, followed, and completed:

Transition from Divi 4 to Divi 5​

In Divi 4, the custom CSS fields are defined in $custom_css_fields variable within the PHP module class. It uses the %%order_class%% selector placeholder to set the order-class position in the selector property.

In Divi 5, the custom CSS fields are defined in customCssFields property of the module.json file, making the process more streamlined and modular. The %%order_class%% selector placeholder maps to {{selector}} for the full order class in context. You can also use {{baseSelector}} for the unprefixed module class and customPostTypeSelector for CPT-specific templates. In the Visual Builder, pass baseOrderClass and isCustomPostType into <CssStyle />. On the frontend (PHP), pass the same values into CssStyle::style() from the $args array your module_styles callback receives from Module::render (covered below).

Custom CSS Styles Explanation​

CssStyle Component and Class​

<CssStyle> component in VB and CssStyle::style() on the frontend (PHP) render custom CSS for the module. Prop names match between JS and the PHP $args array keys (types: JS boolean / string ↔ PHP bool / string|null).

PropTypeDefault
selectorstring''
selectorsobject{}
selectorFunctionFunctionundefined
attrobjectundefined
asStylebooleantrue
cssFieldsobjectundefined
orderClassstringundefined
baseOrderClassstringundefined
isCustomPostTypebooleanundefined

Explanation of Key Props​

selector Defines the base CSS selector. Used to target the primary element for styling. The base target for the generated CSS rules. For example, if set to .my-class, all styles will apply to elements with that class. This property handle {{selector}} interpolation effectively.

selectors Optional. Specifies different selectors for various breakpoints and states (e.g., desktop, tablet, mobile). Provides flexibility to define selectors for specific breakpoints or states (e.g., hover, focus). This is especially useful for creating responsive designs.

selectorFunction Optional. Dynamically modifies the selector based on selector, state, breakpoint, or attribute values. Allows advanced customization by enabling programmatic modification of the selector during runtime. This is helpful in dynamic scenarios where the selector may need to adapt — for example, placing :hover on a nested child instead of the module root. See Hover Selectors.

attr Contains CSS attributes and their values across breakpoints and states. Stores the CSS properties and values for different breakpoints and states. For example, it can define separate color values for desktop and mobile views.

asStyle Determines whether to render the output as a <style> element (true) or return it as a plain string (false). When true, the component renders a <style> tag in the DOM, directly applying the styles. When false, it returns the CSS rules as a string, allowing them to be used elsewhere.

cssFields Maps CSS field names to corresponding selector suffixes or other metadata. Maps custom CSS field names to additional metadata. This includes suffixes (e.g., :before, :after) or template structures for advanced styling requirements.

orderClass A unique class name on VB and module order class name on FE as identifier ensuring custom styles override default ones. Ensures specificity by appending an additional class name. This guarantees that custom styles override any pre-existing ones in the DOM.

baseOrderClass The module order class without builder or layout prefixes (for example the bare .et_pb_* or extension module class fragment). Required when any customCssFields entry uses {{baseSelector}}. In VB the parent Module supplies it on StylesProps; forward it to <CssStyle />. In PHP, Module::render supplies $args['baseOrderClass']; pass it into CssStyle::style() so frontend output matches the builder.

isCustomPostType Whether the current layout/post context is a custom post type. Forward from StylesProps to <CssStyle /> (VB) or from $args['isCustomPostType'] into CssStyle::style() (PHP) when you define customPostTypeSelector; otherwise the Visual Builder may ignore the CPT template while the server still branches on CPT.

Placeholders in customCssFields​

  • {{selector}} — Replaced with the orderClass you pass into <CssStyle /> or into CssStyle::style() as 'orderClass' (Theme Builder / layout context may include prefixes such as .et-db #et-boc .et-l when that is how orderClass was computed).
  • {{baseSelector}} — Replaced with baseOrderClass. Pass baseOrderClass from StylesProps (VB) or $args['baseOrderClass'] (PHP) whenever metadata uses this placeholder.
  • customPostTypeSelector — Optional per-field template used instead of selector when isCustomPostType is true. Pass isCustomPostType from StylesProps (VB) or $args['isCustomPostType'] (PHP) whenever you define this property.
Hover placement

selectorSuffix is plain text — it does not support placeholders such as {{:hover}}. Putting {{:hover}} in customCssFields.selector is also unsupported for this API. To place :hover on a nested element, use selectorFunction or CssStyle selectors as described in Hover Selectors.

For field-level metadata reference, see Custom CSS Fields.

Explanation of cssFields on module.json​

The cssFields prop is an optional mapping object that connects custom CSS field names to their selector suffixes and other metadata. Let's explain how customCssFields of module.json and cssFields of <CssStyle> component or CssStyle class work together:

  1. customCssFields in module.json:

    • Contains custom CSS field definitions for the module.
    • Maps custom CSS field names to their corresponding selector suffixes.
    • Supports {{selector}} interpolation for dynamic selector placement.
  2. cssFields in <CssStyle> or the cssFields key in CssStyle::style():

    • Pass your module’s custom CSS field map (from module.json / block registration), same shape as customCssFields.
    • Enables {{selector}}, {{baseSelector}}, and CPT branching when combined with orderClass, baseOrderClass, and isCustomPostType.
    • Generates custom CSS rules from the saved css attribute and field metadata.

Below is the explanation of each prop of cssFields:

/module.json
{
"customCssFields": {
"moduleQuickTitle": {
"label": "Module Quick Title",
"subName": "moduleQuickTitle",
"selector": "div{{selector}}",
"selectorSuffix": " .d5_tut_simple_quick_module_title"
}
}
}
PropTypeValue in this FieldDescription
labelstringModule Quick TitleA user-friendly name for the field, displayed in the UI to represent this specific CSS customization.
subNamestringmoduleQuickTitleInternal key or identifier for the field, used programmatically to reference the field in CSS generation logic.
selectorstringdiv{{selector}}The base selector template where {{selector}} is a placeholder replaced dynamically with the actual selector (e.g., orderClass).
selectorSuffixstring'.d5_tut_simple_quick_module_title'A plain-text string appended to the resolved selector (no placeholders). Often used to target specific child elements or classes within the parent selector. For nested :hover placement, see Hover Selectors.

How It Works​

The code example can be found below in our Example Modules Plugin

  1. Example of CssStyle class.

  2. Example of customCssFields in module.json.

  3. Example of CssStyle component.

Update module.json​

To add the module custom CSS fields, add customCssFields prop along with the definition. In addition, you can use {{selector}} placeholder in the selector property to rearrange the order class selector. Here’s an example:

/visual-builder/src/module.json
{
"name": "d5-tut/simple-quick-module",
"d4Shortcode": "d5_tut_simple_quick_module",
"title": "Simple Quick Module",
"titles": "Simple Quick Modules",
"category": "module",
"attributes": {
"module": {
"type": "object",
"selector": "{{selector}}",
"default": {
"meta": {
"adminLabel": {
"desktop": {
"value": "Simple Quick Module"
}
}
}
}
},
"title": {
"type": "object",
"selector": "{{selector}} .d5_tut_simple_quick_module_title",
"attributes": {
"class": "d5_tut_simple_quick_module_title"
},
"tagName": "h2",
"inlineEditor": "plainText",
"elementType": "heading",
"childrenSanitizer": "et_core_esc_previously"
},
"content": {
"type": "object",
"selector": "{{selector}} .d5_tut_simple_quick_module_content",
"attributes": {
"class": "d5_tut_simple_quick_module_content"
},
"tagName": "div",
"inlineEditor": "richText",
"childrenSanitizer": "et_core_esc_previously",
"allowHtml": true
}
},
"customCssFields": {
"moduleQuickTitle": {
"label": "Module Quick Title",
"subName": "moduleQuickTitle",
"selector": "div{{selector}}",
"selectorSuffix": " .d5_tut_simple_quick_module_title"
}
}
}

Key Updates:

  • customCssFields: The customCssFields object serves as a configuration map that defines specific parts of a module for applying custom CSS. Each field within the object includes properties such as label, subName, selector, and selectorSuffix, which together facilitate CSS generation.
  • selector: Set as "div{{selector}}" in the moduleQuickTitle field.
  • Purpose: Allows flexible placement of orderClass within the selector.

Configure CssGroup for Custom CSS​

Integrate the CssGroup component in the module's advanced settings to manage custom CSS. It is React function component that renders module settings advanced panel.

/visual-builder/src/index.jsx
// React function component that renders module settings' advanced panel.
advanced: ({groupConfiguration}) => (
<React.Fragment>
<CssGroup
mainSelector=".d5_tut_simple_quick_module"
cssFields={groupConfiguration?.css?.component?.props?.cssFields}
/>
<VisibilitySettingsGroup />
<TransitionGroup />
<PositionSettingsGroup />
<ScrollSettingsGroup />
</React.Fragment>
)

Add <CssStyle /> component in the Visual Builder (VB)​

  • The <CssStyle /> component should be placed at the very bottom of the <StyleContainer /> component to ensure that the custom CSS values take precedence over default styles.
  • Pass orderClass so the {{selector}} placeholder resolves in metadata.
  • Pass baseOrderClass and isCustomPostType from the same StylesProps the Module component gives your ModuleStyles whenever customCssFields use {{baseSelector}} or customPostTypeSelector (see placeholders above).
/visual-builder/src/styles.jsx
/**
* Simple Quick Module's style components.
*/
const ModuleStyles = ({
attrs,
baseOrderClass,
elements,
isCustomPostType,
mode,
noStyleTag,
orderClass,
settings,
state,
}) => (
<StyleContainer mode={mode} state={state} noStyleTag={noStyleTag}>
{/* Element: Module */}
{elements.style({
attrName: 'module',
styleProps: {
disabledOn: {
disabledModuleVisibility: settings?.disabledModuleVisibility,
},
},
})}

{/* Element: Title */}
{elements.style({
attrName: 'title',
})}

{/* Element: Content */}
{elements.style({
attrName: 'content',
})}

<CssStyle
attr={attrs.css}
baseOrderClass={baseOrderClass}
cssFields={elements?.moduleMetadata?.customCssFields}
isCustomPostType={isCustomPostType}
orderClass={orderClass}
selector={orderClass}
/>
</StyleContainer>
);

Add CssStyle::style Method in Frontend (FE)​

  • The CssStyle::style() call should be placed at the very bottom of the Style::add() method within module_styles() so custom CSS overrides default module styles.
  • Pass orderClass (and selector set to the same full order class string) so {{selector}} resolves.
  • Pass baseOrderClass and isCustomPostType from $args when customCssFields use {{baseSelector}} or customPostTypeSelector, matching the Visual Builder (see placeholders above). Module::render includes these keys on $args for your styles callback.
/server/index.php
/**
* Render module style.
*/
public static function module_styles( $args ) {
$attrs = $args['attrs'] ?? [];
$elements = $args['elements'];

Style::add(
[
'id' => $args['id'],
'name' => $args['name'],
'orderIndex' => $args['orderIndex'],
'storeInstance' => $args['storeInstance'],
'styles' => [
// Module.
$elements->style(
[
'attrName' => 'module',
'styleProps' => [
'disabledOn' => [
'disabledModuleVisibility' => $args['settings']['disabledModuleVisibility'] ?? null,
],
],
]
),
// Title.
$elements->style(
[
'attrName' => 'title',
]
),
// Content.
$elements->style(
[
'attrName' => 'content',
]
),
// Module - Only for Custom CSS.
CssStyle::style(
[
'selector' => $args['orderClass'],
'attr' => $attrs['css'] ?? [],
'cssFields' => self::custom_css(),
'orderClass' => $args['orderClass'],
'baseOrderClass' => $args['baseOrderClass'] ?? null,
'isCustomPostType' => ! empty( $args['isCustomPostType'] ),
]
);
],
]
);
}

Congratulations! You’ve successfully integrated Custom CSS functionality into your Divi 5 module

Adding a selector Property in customCssFields

Custom CSS functionality in Divi 5 empowers developers to enhance module styling by overriding default styles and enabling targeted, dynamic customization. This feature ensures greater flexibility and user control, making modules more adaptable to diverse design requirements.

Got a question or feedback? Ask away!