Is it possible to add inline CSS to into the <head> section of a Drupal 8 page? My expected result should look like this:

.my-custom-class {
  background-color: red;

I've tried to add it to hook_preprocess_HOOK() but it will not show up.

function my_module_preprocess_html(&$variables) {
  $variables['html']['#attached']['css'][] = array(
    'type' => 'inline',
    'every_page' => TRUE,
    'data' => '.my-custom-class { background: ' . $dynamic_color . '; }',

I've tried a few other things but it did not work either. Whats the right way to do this?

  • One way to do this that should actually make your CSS load more quickly is to create a custom theme, then in templates/layout/html.html.twig, put your CSS in <style> tags. Because you aren't importing the CSS in an external file, it will load more quickly. This isn't a best practice, but maybe it should be in some cases. It will give you an edge on speed, which is going to be more important now that Google is going to start using page load times in its ranking process.
    – mckinzie25
    May 25, 2021 at 21:00
  • How is this dynamic?
    – leymannx
    May 26, 2021 at 6:18

1 Answer 1


After doing some more research i've found an answer to my problem. The main reason for not finding a solution was, they don't want you to do this in Drupal 8.

From their documentation:


If the dynamic CSS/JS is built for each request, then you enter the truly advanced territory. This is hard, and for a good reason: per-request dynamic assets have to be built on every single request and therefore slow Drupal down. We want to make it hard to make Drupal slow down, so this is why we don't offer a nice API for this — since we don't want you to do it.

This makes sense and there is a short description how to get it to work anyway but its lacking of an example. This is what i've done to get it to work:

function my_module_page_attachments_alter(array &$page) {
  $background_color = '#000';
  $page['#attached']['html_head'][] = [
      '#tag' => 'style',
      '#value' => '.my-custom-class { background: ' . $background_color . '; }',
  • Thanks. I have successfully applied this method in a hook_ENTITY_TYPE_view_alter implementation. It works great and the result seems to be cached as you would expect: the logic of adding the CSS is executed only once per entity (until you clear your cache of course). May 1, 2018 at 12:18
  • 1
    By the way, a downside of this approach is that you cannot control where it ends up in the HTML head. The Classy theme will place it before normal CSS files. May 1, 2018 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.