We are done with the basics of the HTML tags and now we will be changing the styles of the application using CSS and a stylesheet. The following screenshot shows the final output that we will be creating using CSS and a style sheet:
If you have noticed, the font and color of the title of the UI panel, paragraph text size, and formatting of the subheading has changed as compared to the previous application that we used in the Creating a UI using HTML section. Let's get started.
The best way to include CSS is by inserting the style with the element that you require. For example, for the heading style in the Control panel, we have the h1 tag defined inline with the following tag:
h1("Control panel", style = "color:red; font-family:Impact, Charcoal, sans-serif;")
When using CSS in Shiny, basic CSS rules are applied; for example, a semicolon (;) is used to separate elements. The next method for using CSS is to include it in the head section using the tags command:
tags$head( tags$style(HTML("h3 { color: blue;font-family:courier; text-decoration: underline; }" )) )
You must have noticed that the entire piece of CSS code is included in the head and style tag. The use of the HTML command is to tell Shiny that the command is formatted in HTML and should not be rendered.
The last method of using CSS in Shiny is to use a separate style sheet. For this, we will be using the include command, as follows:
includeCSS("styles.css")
You can use this command anywhere in the code block, but it is advisable to add this command at the top of the UI definition. The style.css file should be present in the same directory that your ui.r file is placed in and not in the www folder.
Writing CSS is quite simple, but the method used depends on the amount of styling used aligned to the application. Your choice depends on where you want to add your CSS. If you are defining a lot of code in a line a number of times, it is advisable to use a proper style sheet. We will be creating an application to download reports in a Word document using R Markdown.