Update: If you like this article, consider learning about How to Make Your CSS Systematically Awesome with SASS.
CSS can be a powerful tool for enhancing your R Shiny apps. In this post I’ll provide a brief overview of CSS and I’ll discuss adding CSS to R Shiny.
For information about a timesaving method to produce CSS please refer to the article about the wonderful SASS (a superset of CSS with a lot more power when it comes to structuring and managing your CSS styles).
R Shiny provides scalability, fast prototyping, and power, but without CSS, it looks like this:
With CSS, it can look like this:
Clearly, CSS allows us to build much more visually appealing products. CSS is as old as HTML itself. Still, it remains highly useful, introduces order into the development process and saves time.
CSS stands for Cascading Style Sheets. It describes how HTML elements are to be displayed (in any media). Every Cascading Style Sheet (whether it is contained in a .css file, or embedded in the head element of an HTML document) is a series of instructions called statements. Every CSS statement consists of two parts – selectors for the elements, and a set of rules for these elements. The part outside of the bracket indicates which elements will be affected, and the part inside of the bracket enumerates the rules that will be applied.
One of the greatest benefits of using CSS is that you can have one set of rules that allows you to control the layout of multiple web pages all at once. So as long as you keep the pages consistent, you won’t have to re-do any of the stylings.
There are currently 3 main ways you can add css styling to your code:
The best way is #3 — adding style sheets to a www directory. However, the two remaining methods can find application in certain scenarios and it is good to be aware of them, both for personal projects and when reviewing the work of other developers.
There are two downsides to adding styling directly to HTML tags. First, it is easy to lose track of them in large projects with a lot of code. Second, they cannot be reused for different objects. If you are planning to use the element in more than one place, you will have to repeat the styling.
This approach is a slight improvement, because you are defining it outside of the actual HTML elements. However, since you are still doing it in the code and not using a separate file, you cannot use cache and optimize the app. Therefore, you are still missing some of the options that make CSS particularly useful.
Using a separate file for the style makes the code much cleaner. It provides a separate place for all the rules, it also facilitates code reuse and caching. Using multiple files allows us to add more structure to the styling process.
I hope you found this information useful. In the next blog post, I will compare CSS with SASS and show you how to use SASS with R.
You can find me on LinkedIn or just leave a comment below.