CSS-in-JS

CSS-in-JS is preferable over plain CSS as it enables for more flexibility and is easyer to maintain.

Let's see, as an example, the different ways you have to change the backgrouns image of the login page.

First let's download a background image an put it in our public directory:

If you wish to do so, you can hot swipe assets that you have placed into your public directory in your Keycloak instance files at:

/opt/keycloak/themes/<name of your theme>/<login|account>/resources/dist

Let's see how we can apply the image using a CSS-in-JS. In this example we'll use @emotion/css.

yarn add @emotion/css
src/login/KcPage.tsx
import { css } from "@emotion/css";
import { Suspense, lazy } from "react";
// ...
export default function KcPage(props: { kcContext: KcContext }) {
    const { kcContext } = props;    
    // ...
    return (
        // ...
        <DefaultPage
            kcContext={kcContext}
            classes={classes}
            // ...
        />
    );
}

const classes = {
    kcBodyClass: css({
        "&&": { // Increace specificity so our rule takes precedence over the default background.
            background: `url(${import.meta.env.BASE_URL}background.png) no-repeat center center fixed`,
        }
    })
} satisfies { [key in ClassKey]?: string };

Result (see testing your theme):

Now let's go a little futher, it's even better to let the bundler generate url for your imports instead of manually referencing files from your public directory. So, let's move the background image in src/login/assets/:

And in our code import it this way:

src/login/KcPage.tsx
import { css } from "@emotion/css";
import backgroundPngUrl from "./assets/background.png";
import { Suspense, lazy } from "react";
// ...
export default function KcPage(props: { kcContext: KcContext }) {
    const { kcContext } = props;    
    // ...
    return (
        // ...
        <DefaultPage
            kcContext={kcContext}
            classes={classes}
            // ...
        />
    );
}

const classes = {
    kcBodyClass: css({
        "&&": {
            background: `url(${backgroundPngUrl}) no-repeat center center fixed`,
        }
    })
} satisfies { [key in ClassKey]?: string };

Now let's see how we can go futher and apply different backgroud on different pages of our theme:

Last updated