Add CSS stylesheets to a module (CKEditor) | Drupal 8

Add CSS stylesheets to a module (CKEditor)

Submitted by editor on Wed, 11/18/2015 - 10:44
Question

How to add a css file / libraries in a module.

There are several ways to do that.

1. Styling a programmatically created block.
1.1 Add a librarie.
 -> Create a file modulename.libraries.yml
-> Add css file, Exemple:
my-block-styling:
  version: 1.x
  css:
    theme:
      css/style.css: {}

1.2 Create CSS file and put it in to the module_folder/css/style.css
1.3 Attach librarie to the block
In your build() methode, add to the output array,
    $output[]['#attached']['library'][] = 'modulename/my-block-styling';

Add / Attaching a library from a Twig template

{{ attach_library('MODULENALE/my-style') }}

To remove a style sheet

stylesheets-remove:
  - '@classy/css/components/tabs.css'
  - core/assets/vendor/normalize-css/normalize.css

Add to a form:
$form['#attached']['library'][] = '<YOUR_THEME_NAME>/<library_name>';

Add CSS Style to CKEditor WYSIWYG

Example:
<?php
use Drupal\editor\Entity\Editor;
/**
 * @param array $css
 * @param Editor $editor
 */
function mymodule_ckeditor_css_alter(array &$css, Editor $editor) {
  $css[] = drupal_get_path('module', 'mymodule') . '/css/ckeditor.css';
}

 

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.