Drupal 8 Quick Tip: Attaching Inline CSS

Drupal 8 does away with drupal_add_css and drupal_add_js (see the change record for more info).  In its place, you'll need to use #attached on render arrays.  While this seems pretty straightforward when adding css stored in files, you might question how to attach inline CSS or JS.  Here's an example:

$css = 'img { outline: 2px solid #F00; }';
$options = array('type' => 'inline');
$build['#attached']['css'][$css] = $options;

For me, this code is in hook_node_view, but it could go anywhere you have a render array. #attached is an element I've added here. It seems likely that you'll find it already exists in some cases.  Same with css or js. Css and js are arrays where the key is the filename or the actual css that you want to add inline.  It's a little unwieldy to be sure, but that's how it works.

As I continue to build this site in Drupal 8, I'll be sure to share anything else I find helpful.  Look forward to a followup post that will explain why your render code might not be behaving predictably!

Edit: Here's an alternate solution courtesy of Michael Grasmick in the comments.

This method allows you to add your element-specific CSS in the header without using "inline" css, and is a bit tidier.

// Assuming your element has the "banner" class
$css = ".banner { background-image: url($picture); }";
$variables['page']['#attached']['html_head'][] = [
    '#tag' => 'style',
    '#value' => $css,

Discover more of the ways we use Drupal to innovate.