Add custom CSS Class to any Page

it is possible to add a custom css class to a page from backend?

Home <-- main
Contact <-- sub

Yes, it is possible. You can do this by using the $page->template() function. If you do not have a custom template, you could instead use the $page->uid() function.

Here’s a basic example on how to achieve this:


    if ( $page->template() == 'contact'  ) {
        $class = 'sub';
    } else {
        $class = 'main';


<main class="<?php echo $class ?>">
    Your content.

Edit: Sorry, I was using the wrong function. My mistake for not checking my code before posting :sweat: I have corrected the code and function.

If you don’t want to use the template, but have individual classes for your pages, you can also use the page UID, or the value of any field of your pages.

Do you have a snippet?

this could work, i think…

*Wondering about the fast response in this community. :kissing_smiling_eyes:

<main class="<?= $page->uid() ?>">
    Your content.

There is one caveat to using any of these solutions: If the UID or the template is changed, the css class is worthless. For those pages where having a class is crucial, make sure to disallow temlate/UID change or use a read only field in your files.

Just a tiny typo

<main class="<?= $page->uid() ?>">
    Your content.

I use something similar (i’m also outputing the template name) but on my root element instead

<html class="<?= $page->uid() ?>">

@JimmyRittenborg oops, yes, thanks, I have corrected it above.

1 Like