How to Create Dynamic CSS Styles

If you’re looking to dynamically change your CSS styles based on the current page URL in WordPress, you’re in the right place. In this guide, we’ll walk through a step-by-step process using vanilla JavaScript and the HFCM plugin.

Setting Up

Select Head Element

To begin, we need to select the <head> element where we’ll be inserting our dynamically created styles. To accomplish this, we can use the following JavaScript:

const head = document.querySelector(“head”);

Create Style Element Dynamically

Next, let’s create a <style> tag using JavaScript dynamically:

const styleElement = document.createElement(‘style’);

Append Style Tag to Head

Now, we’ll append our newly created <style> tag to the <head> element:


Creating Page Objects

We’ll define a JavaScript function for creating page objects, each with three properties: URL, color, and rgba.

function Page(url, color, rgba) {
this.url = url;
this.color = color;
this.rgba = rgba;
Now, let’s create page objects for different pages on our website:
const about = new Page(“”, “–about”, “–aboutRGBA”);
const gallery = new Page(“”, “–gallery”, “–galleryRGBA”);
const contact = new Page(“”, “–contact”, “–contactRGBA”);
const faq = new Page(“”, “–faq”, “–faqRGBA”);
const home = new Page(“”, “–home”, “–homeRGBA”);

Iterating Over Pages

Now, let’s create an array of these page objects:

const pages = [home, about, gallery, contact, faq];

Now, we can then iterate over these pages and dynamically generate CSS based on the current URL:

for (const page of pages) {
const currentUrl = window.location.href;

if (currentUrl === page.url) {
// Dynamically create CSS based on the current page
const links = document.createTextNode(`a , {color: var(${page.color});}`);
const hamburger = document.createTextNode(`.mobile_menu_bar:before, .mobile_menu_bar:after, .et_toggle_slide_menu:after {color: var(${page.color});}`);
const formButton = document.createTextNode(`#gform_1 input[type=submit] { border-color: var(${page.color}); background-color: var(${page.color});}`);
const sideMenu = document.createTextNode(`.et_slide_in_menu_container, #top-header {background-color: var(${page.color});}`);

// Array of styles
const styles = [links, hamburger, formButton, sideMenu];

// Append styles to the dynamically created <style> tag
for (const style of styles) {

And that’s it! You’ve successfully created dynamic CSS styles that change based on the current page URL using vanilla JavaScript and the HFCM plugin in WordPress. Feel free to customize the colors and styles to match your website’s design.

After reading what you’ve read, do you have any additional questions about WordPress? Contact Beanstalk and let’s chat.