原始文章鏈接
http://shiny.rstudio.com/articles/css.html
寫在前面
shiny 是基于Bootstrap 3.3.1,所以想使用其他css或者Bootstrap4 的樣式,就需要自己添加了。
三種方法
一、在head中鏈接css文件
-
將css文件放到同級(jí)www文件夾下面,通過 theme = "bootstrap.css" 來引入css。如下圖。但是如果你想用shinythemes 帶的樣式就要寫成這樣,theme = shinythemes::shinytheme("cosmo"),這樣我們只能選其一。
image
shinyUI(fluidPage(theme = "bootstrap.css",
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
mainPanel(plotOutput("distPlot"))
))
- 當(dāng)然還可以通過tags對(duì)象在head中鏈接CSS文件,沒有上面提到的沖突。需要注意的一點(diǎn)是,www文件夾下面文件引入時(shí),路徑直接為“filename”,而不是“www/filename”,引入圖片等都是這樣。
shinyUI(fluidPage(
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "bootstrap.css")
),
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
mainPanel(plotOutput("distPlot"))
))
對(duì)應(yīng)的HTML就如下
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap.css"/>
</head>
<body>
</body>
</html>
二、直接在head中寫入css樣式
- 使用style標(biāo)簽
shinyUI(fluidPage(
tags$head(
tags$style(HTML("
@import url('//fonts.googleapis.com/css?family=Lobster|Cabin:400,700');
h1 {
font-family: 'Lobster', cursive;
font-weight: 500;
line-height: 1.1;
color: #48ca3b;
"))
),
-
使用函數(shù) includeCSS,這種方法要求讀入的css文件不必放在www文件夾下。這個(gè)方法和方法一中通過tags$link方法的區(qū)別是,此方法直接將css文件中所有的文本copy過來寫入到head中,而不是一個(gè)鏈接。
image
shinyUI(fluidPage(
includeCSS("styles.css"),
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
mainPanel(plotOutput("distPlot"))
))
三、直接寫在不同的元素中而不是全局的head中
例如想修改某一個(gè)h標(biāo)簽的樣式。
headerPanel(
h1("New Application",
style = "font-family: 'Lobster', cursive;
font-weight: 500; line-height: 1.1;
color: #4d3a7d;")),
最后
注意css樣式?jīng)_突時(shí)的優(yōu)先級(jí)就行了。

