Add css style to theme in module I'm writing a module that contains a star field. Now I'm placing the stars using the viewElements function of my field formatter. Everything is working. But I need to place some syling to the field output. Can I send some css styling to the active theme using my module?

My field formatter looks like:

public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta =&gt; $item) {
    $total = $item-&gt;rating/2;

    $stars = '';

    //Place colored stars
    for($i =0; $i &lt; floor($total); $i++)
    {
        $stars .= '&lt;span class="star on"&gt;&lt;/span&gt;';
    }

    //Place half star
    if(floor($total) != $total)
    {
       $stars .= '&lt;span class="star half"&gt;&lt;/span&gt;';
    }

    //Place open stars
    for($i = ceil($total); $i &lt; 5; $i++)
    {
        $stars .= '&lt;span class="star"&gt;&lt;/span&gt;';
    }

      $element[$delta] = array(
        '#markup' =&gt; $stars,
      );
    }
    return $element;
  }


The only thing that I'm missing is the css style that looks like:

.star {
    font-size: x-large;
    width: 50px;
    display: inline-block;
    color: gray;
}
.star:last-child {
    margin-right: 0;
}
.star:before {
    content:'\2605';
}
.star.on {
    color: gold;
}
.star.half:after {
    content:'\2605';
    color: gold;
    position: absolute;
    margin-left: -20px;
    width: 10px;
    overflow: hidden;
}
To do this, you need to create a *.libraries.yml file, with the path to your css file in it:

MODULE.libaries.yml:

star-field:
  version: Version
  css:
    theme:
      path/to/stylesheet.css: {}


Then you can attach that library to your element:

$element['#attached']['library'][] = MODULE/star-field;


This can be overridden in a theme if/when necessary, so this styling should be considered the default styling that the module creates.

More reading: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module