Log in Sign up

Changing background color with metadata?

Hello! Using a custom template here, based on an old version of the Essay template.

I'm wondering if there's a way to specify an individual post's background color using Blot metadata. I'm already using the variable bg color in my CSS, but it grabs what color is specified in the template setting. (I'm overriding this on the template's dark mode variant).

body {
  background: {{background_color}};
}

What I'd like to do is specify a color in each post's metadata, which then gets loaded in place of that CSS variable.

Any help would be much appreciated!


2 years ago, 3 replies   developers   metadata   Edit question

This is possible and your solution makes sense but won't work because your template's CSS file is not rendered with a given entry's data.

Do you want to be able to define the background color in a post's metadata in an abstract way? Or in a specific way, by providing a CSS color value, e.g. #FF0000?

If you want the abstract approach, you could do something like this in your template's entry.html file:

<!DOCTYPE html>
<html>
  {{> head}}
  <body class="{{#entry.metadata.color}}{{.}}{{/entry.metadata.color}}">
    <div class="container">
    {{> header}}
...

And then in your CSS file:

body.red {background: #f00}
body.green {background: #0f0}
body.blue {background: #00f}

And then in a post's metadata:

Color: blue

If however you want to do something specific, I'd suggest this approach instead in your template's entry.html file:

...
{{#entry.metadata.color}}
<style type="text/css">
body {
  background-color: {{.}};
}
</style>
{{/entry.metadata.color}}
...

And then in a post's metadata:

Color: #f00

Does that make sense? Please let me know if you have any questions about this or anything else

Answered 2 years ago · Edit answer

Went for the first option and it works like a charm, thank you very much for the help!

Only problem is that this color overrides my CSS dark mode settings, but I’m thinking there might be a way to override the bg color in dark mode—will need to research that. Deactivated dark mode for the time being.

Much appreciated!

Answered 2 years ago · Edit answer

Sounds like you're running into a problem with the 'cascading' aspect of Cascading Style Sheets! Please let me know if you need help working this out – my first suggestion would be to inspect the element in question using your browser developer tools to understand the 'cascade' of style rules.

Answered 2 years ago · Edit answer