A very typical scenario is that you are a teacher in a Moodle course or content expert, but you do not have administration access to the Moodle platform but you really want or need to add a CSS style to something in your course content.

You tried adding CSS to a page but it was automatically stripped out.

One option to try is to ask your administrator to add a HTML Block (or you can add it yourself if you have permissions) into your course that appears on every page. Tell them you need it for a general course announcement that you want in your course.

Once the Block has been added, turn editing on and select ‘Configure Course Message block’

You will want the Block to appear on every page in your course so that the CSS is applied to every page.

Now that you have a Block that appears on every page, you can use this to store your CSS.

Make sure you have ‘Turn editing on’ before you continue.

 

By configuring the HTML Block and selecting the ‘Advanced buttons’ arrow and the HTML edit code button </>. You are ready to add your own CSS to your course.

As an example, let’s add this code to the HTML in our HTML Block.

 

<p class="bigbluetext">Big blue text</p>

<script type="text/javascript">

    var cssRules =

        '.bigbluetext{font-size:x-large;color:blue;}';

    var styleElement = document.createElement('style');

    styleElement.appendChild(document.createTextNode(cssRules));

    document.getElementsByTagName('head')[0].appendChild(styleElement);

</script>

Or try the variation with CDATA

<script type="text/javascript">// <![CDATA[
    var cssRules =
   '.bigbluetext{font-size:x-large;color:blue;}';
    var styleElement = document.createElement('style');
    styleElement.appendChild(document.createTextNode(cssRules));
    document.getElementsByTagName('head')[0].appendChild(styleElement);
// ]]></script>

Select save and you will see the following displayed in Moodle.

This adds a class called bigbluetext and changes the text in the course message that has class=”bigbluetext” into an x-large blue font.

To add to the CSS, just add your normal CSS code in between the single quotes after  var cssRules = ‘.bigbluetext{font-size:x-large;color:blue;}’;

  • Make sure you keep all the CSS on the same line.
  • To change the page header colour, find the class used for the page header. .page-header-headings

Then add this to the CSS string. 

cssRules = '.bigbluetext{font-size:x-large;color:blue;}.page-header-headings{color:#ff0000;}';

Save the page to view the CSS changes.

Anything you can imagine with CSS can be applied, although remember that if the Theme is modified, updated or changed, then the classes may change as well.

I hope you find this useful.

Please feel free to contact me if you have any questions.