shiny-bslib-theming

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Theming Shiny Apps with bslib

使用bslib为Shiny应用定制主题

Customize Shiny app appearance using bslib's Bootstrap 5 theming system. From quick Bootswatch themes to advanced Sass customization and dynamic color mode switching.
借助bslib的Bootstrap 5主题系统自定义Shiny应用的外观,从快速应用Bootswatch主题到高级Sass自定义、动态色彩模式切换都可实现。

Quick Start

快速开始

"shiny" preset (recommended starting point):
r
page_sidebar(
  theme = bs_theme(),  # "shiny" preset by default — polished, not plain Bootstrap
  ...
)
Bootswatch theme (for a different visual style):
r
page_sidebar(
  theme = bs_theme(preset = "zephyr"),  # or "cosmo", "minty", "darkly", etc.
  ...
)
Custom colors and fonts:
r
page_sidebar(
  theme = bs_theme(
    version = 5,
    bg = "#FFFFFF",
    fg = "#333333",
    primary = "#2c3e50",
    base_font = font_google("Lato"),
    heading_font = font_google("Montserrat")
  ),
  ...
)
Auto-brand from
_brand.yml
:
If a
_brand.yml
file exists in your app or project directory,
bs_theme()
automatically discovers and applies it. No code changes needed. Requires the
brand.yml
R package.
r
bs_theme(brand = FALSE)    # Disable auto-discovery
bs_theme(brand = TRUE)     # Require _brand.yml (error if not found)
bs_theme(brand = "path/to/brand.yml")  # Explicit path
"shiny"预设(推荐的入门选择):
r
page_sidebar(
  theme = bs_theme(),  # 默认使用"shiny"预设,效果精致,不是原生Bootstrap
  ...
)
Bootswatch主题(用于实现不同的视觉风格):
r
page_sidebar(
  theme = bs_theme(preset = "zephyr"),  # 也可选"cosmo"、"minty"、"darkly"等
  ...
)
自定义颜色和字体:
r
page_sidebar(
  theme = bs_theme(
    version = 5,
    bg = "#FFFFFF",
    fg = "#333333",
    primary = "#2c3e50",
    base_font = font_google("Lato"),
    heading_font = font_google("Montserrat")
  ),
  ...
)
_brand.yml
自动加载品牌配置:
如果你的应用或项目目录下存在
_brand.yml
文件,
bs_theme()
会自动识别并应用配置,无需修改代码。需要安装
brand.yml
R包。
r
bs_theme(brand = FALSE)    # 关闭自动识别
bs_theme(brand = TRUE)     # 强制要求存在_brand.yml,找不到则报错
bs_theme(brand = "path/to/brand.yml")  # 显式指定文件路径

Theming Workflow

主题配置工作流

  1. Start with the
    "shiny"
    preset (default) or a Bootswatch theme close to your desired look
  2. Customize main colors (
    bg
    ,
    fg
    ,
    primary
    )
  3. Adjust fonts with
    font_google()
    or other font helpers
  4. Fine-tune with Bootstrap Sass variables via
    ...
    or
    bs_add_variables()
  5. Add custom Sass rules with
    bs_add_rules()
    if needed
  6. Enable
    thematic::thematic_shiny()
    so plots match the theme
  7. Use
    bs_themer()
    during development for interactive preview
Example:
r
theme <- bs_theme(preset = "minty") |>
  bs_theme_update(
    primary = "#1a9a7f",
    base_font = font_google("Lato")
  ) |>
  bs_add_rules("
    .card { box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  ")
  1. 从"shiny"预设(默认)或接近你预期效果的Bootswatch主题开始
  2. 自定义主色调(
    bg
    fg
    primary
  3. 通过
    font_google()
    或其他字体工具调整字体配置
  4. 通过
    ...
    参数或
    bs_add_variables()
    微调Bootstrap Sass变量
  5. 如有需要用
    bs_add_rules()
    添加自定义Sass规则
  6. 启用
    thematic::thematic_shiny()
    让绘图样式匹配主题
  7. 开发过程中使用
    bs_themer()
    进行交互式预览
示例:
r
theme <- bs_theme(preset = "minty") |>
  bs_theme_update(
    primary = "#1a9a7f",
    base_font = font_google("Lato")
  ) |>
  bs_add_rules("
    .card { box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  ")

bs_theme()

bs_theme()

Central function for creating Bootstrap themes. Returns a
sass::sass_bundle()
object.
r
bs_theme(
  version = version_default(),
  preset = NULL,        # "shiny" (default for BS5+), "bootstrap", or Bootswatch name
  ...,                  # Bootstrap Sass variable overrides
  brand = NULL,         # brand.yml: NULL (auto), TRUE (require), FALSE (disable), or path
  bg = NULL, fg = NULL,
  primary = NULL, secondary = NULL,
  success = NULL, info = NULL, warning = NULL, danger = NULL,
  base_font = NULL, code_font = NULL, heading_font = NULL,
  font_scale = NULL,    # Scalar multiplier for base font size (e.g., 1.5 = 150%)
  bootswatch = NULL     # Alias for preset
)
Use
bs_theme_update(theme, ...)
to modify an existing theme. Use
is_bs_theme(x)
to test if an object is a theme.
创建Bootstrap主题的核心函数,返回一个
sass::sass_bundle()
对象。
r
bs_theme(
  version = version_default(),
  preset = NULL,        # "shiny"(BS5+版本默认)、"bootstrap"或Bootswatch主题名
  ...,                  # Bootstrap Sass变量覆盖配置
  brand = NULL,         # brand.yml配置:NULL(自动识别)、TRUE(强制要求)、FALSE(关闭)或文件路径
  bg = NULL, fg = NULL,
  primary = NULL, secondary = NULL,
  success = NULL, info = NULL, warning = NULL, danger = NULL,
  base_font = NULL, code_font = NULL, heading_font = NULL,
  font_scale = NULL,    # 基础字体大小的缩放系数(例如1.5 = 放大到150%)
  bootswatch = NULL     # preset的别名
)
使用
bs_theme_update(theme, ...)
修改已有主题,使用
is_bs_theme(x)
判断对象是否为合法主题。

Presets and Bootswatch

预设与Bootswatch

The "shiny" preset (recommended):
bs_theme()
defaults to
preset = "shiny"
for Bootstrap 5+. This is a polished, purpose-built theme designed specifically for Shiny apps — it is not plain Bootstrap. It provides professional styling with well-chosen defaults for cards, sidebars, value boxes, and other bslib components. Start here and customize with colors and fonts before reaching for a Bootswatch theme.
Vanilla Bootstrap: Use
preset = "bootstrap"
to remove the "shiny" preset and get unmodified Bootstrap 5 styling.
Built-in presets:
builtin_themes()
lists bslib's own presets.
Bootswatch themes:
bootswatch_themes()
lists all available Bootswatch themes. Choose one that fits the app's purpose and audience — don't apply one by default.
Popular options:
"zephyr"
(light, modern),
"cosmo"
(clean),
"minty"
(fresh green),
"flatly"
(flat design),
"litera"
(crisp),
"darkly"
(dark),
"cyborg"
(dark),
"simplex"
(minimalist),
"sketchy"
(hand-drawn).
"shiny"预设(推荐): Bootstrap 5及以上版本的
bs_theme()
默认使用
preset = "shiny"
,这是专门为Shiny应用设计的定制主题,并非原生Bootstrap。它为卡片、侧边栏、数值框等bslib组件提供了专业的默认样式,建议先从这个预设开始,自定义颜色和字体后再考虑使用Bootswatch主题。
原生Bootstrap: 使用
preset = "bootstrap"
可以移除"shiny"预设,获得未经修改的Bootstrap 5样式。
内置预设:
builtin_themes()
可以列出bslib自带的所有预设。
Bootswatch主题:
bootswatch_themes()
列出所有可用的Bootswatch主题,选择符合应用用途和受众的主题即可,无需默认应用。
热门选项:
"zephyr"
(浅色现代风)、
"cosmo"
(简洁风)、
"minty"
(清新绿风格)、
"flatly"
(扁平化设计)、
"litera"
(清晰风)、
"darkly"
(深色主题)、
"cyborg"
(深色主题)、
"simplex"
(极简风)、
"sketchy"
(手绘风)。

Main Colors

主色调配置

The most influential colors — changing these affects hundreds of CSS rules via variable cascading:
ParameterDescription
bg
Background color
fg
Foreground (text) color
primary
Primary brand color (links, nav active states, input focus)
secondary
Default for action buttons
success
Positive/success states (typically green)
info
Informational content (typically blue-green)
warning
Warnings (typically yellow)
danger
Errors/destructive actions (typically red)
r
bs_theme(
  bg = "#202123", fg = "#B8BCC2",
  primary = "#EA80FC", secondary = "#48DAC6"
)
Color tips:
  • bg
    /
    fg
    : similar hue, large luminance difference (ensure contrast for readability)
  • primary
    : contrasts with both
    bg
    and
    fg
    ; used for hyperlinks, navigation, input focus
  • Colors can be any format
    htmltools::parseCssColors()
    understands
这是影响力最大的颜色配置——修改这些参数会通过变量级联影响数百条CSS规则:
参数描述
bg
背景色
fg
前景(文本)色
primary
主品牌色(链接、导航激活态、输入框聚焦态)
secondary
操作按钮默认色
success
正向/成功状态色(通常为绿色)
info
信息类内容色(通常为蓝绿色)
warning
警告状态色(通常为黄色)
danger
错误/破坏性操作色(通常为红色)
r
bs_theme(
  bg = "#202123", fg = "#B8BCC2",
  primary = "#EA80FC", secondary = "#48DAC6"
)
颜色配置提示:
  • bg
    /
    fg
    :色相相近,亮度差异大(确保可读性对比度)
  • primary
    :需同时和
    bg
    fg
    形成对比,用于超链接、导航、输入框聚焦态
  • 颜色支持
    htmltools::parseCssColors()
    识别的所有格式

Typography

排版配置

Three font arguments:
base_font
,
heading_font
,
code_font
. Use
font_scale
to uniformly scale all font sizes (e.g.,
1.5
for 150%).
Each argument accepts a single font, a
font_collection()
, or a character vector of font names.
提供三个字体参数:
base_font
heading_font
code_font
。使用
font_scale
可以统一缩放所有字体大小(例如
1.5
对应放大到150%)。
每个参数可接受单个字体、
font_collection()
或字体名称的字符向量。

font_google()

font_google()

Downloads and caches Google Fonts locally (
local = TRUE
by default). Internet needed only on first download.
r
bs_theme(
  base_font = font_google("Roboto"),
  heading_font = font_google("Montserrat"),
  code_font = font_google("Fira Code")
)
With variable weights:
font_google("Crimson Pro", wght = "200..900")
With specific weights:
font_google("Raleway", wght = c(300, 400, 700))
Recommend fallbacks to avoid Flash of Invisible Text (FOIT) on slow connections:
r
bs_theme(
  base_font = font_collection(
    font_google("Lato", local = FALSE),
    "Helvetica Neue", "Arial", "sans-serif"
  )
)
Font pairing resource: fontpair.co
下载并本地缓存Google Fonts(默认
local = TRUE
),仅首次下载需要联网。
r
bs_theme(
  base_font = font_google("Roboto"),
  heading_font = font_google("Montserrat"),
  code_font = font_google("Fira Code")
)
可变字重示例:
font_google("Crimson Pro", wght = "200..900")
指定字重示例:
font_google("Raleway", wght = c(300, 400, 700))
建议添加 fallback 字体,避免网络慢时出现FOIT(无样式文本闪烁):
r
bs_theme(
  base_font = font_collection(
    font_google("Lato", local = FALSE),
    "Helvetica Neue", "Arial", "sans-serif"
  )
)
字体搭配资源:fontpair.co

font_link()

font_link()

CSS web font interface for custom font URLs:
r
font_link("Crimson Pro",
  href = "https://fonts.googleapis.com/css2?family=Crimson+Pro:wght@200..900")
用于自定义字体URL的CSS网络字体接口:
r
font_link("Crimson Pro",
  href = "https://fonts.googleapis.com/css2?family=Crimson+Pro:wght@200..900")

font_face()

font_face()

For locally hosted font files with full
@font-face
control:
r
font_face(
  family = "Crimson Pro",
  style = "normal",
  weight = "200 900",
  src = "url(fonts/crimson-pro.woff2) format('woff2')"
)
用于本地托管的字体文件,可完全控制
@font-face
配置:
r
font_face(
  family = "Crimson Pro",
  style = "normal",
  weight = "200 900",
  src = "url(fonts/crimson-pro.woff2) format('woff2')"
)

font_collection()

font_collection()

Combine multiple fonts with fallback order:
r
font_collection(font_google("Lato"), "Helvetica Neue", "Arial", "sans-serif")
按 fallback 顺序组合多个字体:
r
font_collection(font_google("Lato"), "Helvetica Neue", "Arial", "sans-serif")

Low-Level Theming Functions

底层主题定制函数

For customizations beyond
bs_theme()
's named parameters. These work directly with Bootstrap's Sass layers.
用于
bs_theme()
命名参数之外的自定义需求,可直接操作Bootstrap的Sass层。

bs_add_variables()

bs_add_variables()

Add or override Bootstrap Sass variable defaults:
r
theme <- bs_add_variables(
  bs_theme(preset = "sketchy", primary = "orange"),
  "body-bg" = "#EEEEEE",
  "font-family-base" = "monospace",
  "font-size-base" = "1.4rem",
  "btn-padding-y" = ".16rem"
)
The
.where
parameter
controls placement in the Sass compilation order:
.where
When to use
"defaults"
(default)
Set variable defaults with
!default
flag. Placed before Bootstrap's own defaults.
"declarations"
Reference other Bootstrap variables (e.g.,
$secondary
). Placed after Bootstrap's defaults.
"rules"
Placed after all rules. Rarely needed.
Referencing Bootstrap variables:
r
undefined
添加或覆盖Bootstrap Sass变量默认值:
r
theme <- bs_add_variables(
  bs_theme(preset = "sketchy", primary = "orange"),
  "body-bg" = "#EEEEEE",
  "font-family-base" = "monospace",
  "font-size-base" = "1.4rem",
  "btn-padding-y" = ".16rem"
)
.where
参数
控制Sass编译顺序中的位置:
.where
取值
使用场景
"defaults"
(默认)
!default
标记设置变量默认值,放在Bootstrap自有默认值之前
"declarations"
引用其他Bootstrap变量(例如
$secondary
),放在Bootstrap默认值之后
"rules"
放在所有规则之后,很少使用
引用Bootstrap变量示例:
r
undefined

This fails in bs_theme() because $secondary isn't defined yet:

直接在bs_theme()中使用会失败,因为$secondary还未定义:

bs_theme("progress-bar-bg" = "$secondary")

bs_theme("progress-bar-bg" = "$secondary")

Use bs_add_variables with .where = "declarations" instead:

改为使用.where = "declarations"的bs_add_variables:

bs_theme() |> bs_add_variables("progress-bar-bg" = "$secondary", .where = "declarations")
undefined
bs_theme() |> bs_add_variables("progress-bar-bg" = "$secondary", .where = "declarations")
undefined

bs_add_rules()

bs_add_rules()

Add custom Sass/CSS rules that can reference Bootstrap variables and mixins:
r
theme <- bs_theme(primary = "#007bff") |>
  bs_add_rules("
    .custom-card {
      background: mix($bg, $primary, 95%);
      border: 1px solid $primary;
      padding: $spacer;

      @include media-breakpoint-up(md) {
        padding: $spacer * 2;
      }
    }
  ")
From external file:
bs_add_rules(sass::sass_file("www/custom.scss"))
Available Sass functions:
lighten()
,
darken()
,
mix()
,
rgba()
,
color-contrast()
. Available Bootstrap mixins:
@include media-breakpoint-up()
,
@include box-shadow()
,
@include border-radius()
.
添加可引用Bootstrap变量和混合宏的自定义Sass/CSS规则:
r
theme <- bs_theme(primary = "#007bff") |>
  bs_add_rules("
    .custom-card {
      background: mix($bg, $primary, 95%);
      border: 1px solid $primary;
      padding: $spacer;

      @include media-breakpoint-up(md) {
        padding: $spacer * 2;
      }
    }
  ")
从外部文件加载:
bs_add_rules(sass::sass_file("www/custom.scss"))
可用的Sass函数:
lighten()
darken()
mix()
rgba()
color-contrast()
。 可用的Bootstrap混合宏:
@include media-breakpoint-up()
@include box-shadow()
@include border-radius()

bs_add_functions() and bs_add_mixins()

bs_add_functions() 和 bs_add_mixins()

Add custom Sass functions or mixins to the theme bundle:
r
theme |>
  bs_add_functions("@function my-tint($color) { @return mix(white, $color, 20%); }") |>
  bs_add_rules(".highlight { background: my-tint($primary); }")
向主题包中添加自定义Sass函数或混合宏:
r
theme |>
  bs_add_functions("@function my-tint($color) { @return mix(white, $color, 20%); }") |>
  bs_add_rules(".highlight { background: my-tint($primary); }")

bs_bundle()

bs_bundle()

Append
sass::sass_bundle()
objects to a theme (for packaging reusable theme extensions):
r
my_extension <- sass::sass_layer(
  defaults = list("my-var" = "red !default"),
  rules = ".my-class { color: $my-var; }"
)
theme <- bs_theme() |> bs_bundle(my_extension)
sass::sass_bundle()
对象追加到主题中(用于封装可复用的主题扩展):
r
my_extension <- sass::sass_layer(
  defaults = list("my-var" = "red !default"),
  rules = ".my-class { color: $my-var; }"
)
theme <- bs_theme() |> bs_bundle(my_extension)

Bootstrap Sass Variables

Bootstrap Sass变量

Pass any Bootstrap 5 Sass variable through
bs_theme(...)
or
bs_add_variables()
.
Common variables:
r
bs_theme(
  "border-radius" = "0.5rem",
  "card-border-radius" = "1rem",
  "card-bg" = "lighten($bg, 5%)",
  "navbar-bg" = "$primary",
  "link-color" = "$primary",
  "font-size-base" = "1rem",
  "spacer" = "1rem",
  "btn-padding-y" = ".5rem",
  "btn-padding-x" = "1rem",
  "input-border-color" = "#dee2e6"
)
Values can be Sass expressions referencing variables, functions, and math.
可通过
bs_theme(...)
bs_add_variables()
传入任意Bootstrap 5 Sass变量。
常用变量示例:
r
bs_theme(
  "border-radius" = "0.5rem",
  "card-border-radius" = "1rem",
  "card-bg" = "lighten($bg, 5%)",
  "navbar-bg" = "$primary",
  "link-color" = "$primary",
  "font-size-base" = "1rem",
  "spacer" = "1rem",
  "btn-padding-y" = ".5rem",
  "btn-padding-x" = "1rem",
  "input-border-color" = "#dee2e6"
)
变量值可以是引用变量、函数、数学运算的Sass表达式。

Bootstrap CSS Custom Properties

Bootstrap CSS自定义属性

See sass-and-css-variables.md for details on:
  • How Sass variables compile into
    --bs-*
    CSS custom properties
  • Runtime vs compile-time variable layers
  • How Bootstrap 5.3 color modes use CSS variable overrides
  • Per-element theming with
    data-bs-theme
  • CSS utility classes for one-off styling
参考sass-and-css-variables.md了解以下内容的详情:
  • Sass变量如何编译为
    --bs-*
    开头的CSS自定义属性
  • 运行时 vs 编译时变量层
  • Bootstrap 5.3色彩模式如何使用CSS变量覆盖
  • data-bs-theme
    实现单元素主题定制
  • 用于一次性样式调整的CSS工具类

Dark Mode and Color Modes

深色模式与色彩模式

See dark-mode.md for details on:
  • Bootstrap 5.3's client-side color mode system (
    data-bs-theme
    attribute)
  • input_dark_mode()
    and
    toggle_dark_mode()
    for user-controlled switching
  • Server-side theme switching with
    session$setCurrentTheme()
  • Writing custom Sass that works across light/dark modes
  • Component compatibility (what responds to theming, what doesn't)
参考dark-mode.md了解以下内容的详情:
  • Bootstrap 5.3的客户端色彩模式系统(
    data-bs-theme
    属性)
  • 供用户切换的
    input_dark_mode()
    toggle_dark_mode()
  • 通过
    session$setCurrentTheme()
    实现服务端主题切换
  • 编写可同时适配亮/深色模式的自定义Sass
  • 组件兼容性(哪些组件支持主题适配,哪些不支持)

Theming R Plots

R绘图主题适配

bs_theme()
only affects CSS. R plot output (rendered server-side as images) won't auto-match. Use the
thematic
package:
r
library(thematic)
thematic_shiny(font = "auto")  # Call before shinyApp()
shinyApp(ui, server)
  • Works with base R, ggplot2, and lattice
  • Translates CSS colors into R plotting defaults
  • font = "auto"
    also matches fonts from
    bs_theme()
  • Complements
    bs_themer()
    for real-time preview
Set global ggplot2 theme for further consistency:
r
library(ggplot2)
theme_set(theme_minimal())
bs_theme()
仅影响CSS,R绘图输出(服务端渲染为图片)不会自动匹配主题,可使用
thematic
包:
r
library(thematic)
thematic_shiny(font = "auto")  # 在shinyApp()调用前执行
shinyApp(ui, server)
  • 支持base R、ggplot2和lattice绘图库
  • 将CSS颜色转换为R绘图默认配置
  • font = "auto"
    还可自动匹配
    bs_theme()
    中的字体设置
  • 可配合
    bs_themer()
    实现实时预览
设置全局ggplot2主题进一步提升一致性:
r
library(ggplot2)
theme_set(theme_minimal())

Dashboard Background Styling

仪表盘背景样式

The
bslib-page-dashboard
CSS class adds a light gray background behind the main content area, giving dashboard-style apps a polished look where cards stand out against the background. This is a theming detail — it doesn't change layout behavior, only the visual treatment.
For
page_sidebar()
dashboards:
r
page_sidebar(
  class = "bslib-page-dashboard",
  title = "My Dashboard",
  sidebar = sidebar(...),
  ...
)
For
page_navbar()
with dashboard-focused pages:
Apply the class to individual
nav_panel()
containers (not
page_navbar()
itself) so only dashboard-oriented pages get the gray background:
r
page_navbar(
  title = "Analytics",
  nav_panel("Dashboard", class = "bslib-page-dashboard",
    layout_column_wrap(...)
  ),
  nav_panel("Report",
    # No dashboard class — standard white background for prose/reports
    ...
  )
)
bslib-page-dashboard
CSS类会在主内容区域后添加浅灰色背景,让仪表盘类应用的卡片在背景上更突出,视觉效果更精致。这是主题层面的配置,不会影响布局行为,仅改变视觉效果。
针对
page_sidebar()
仪表盘:
r
page_sidebar(
  class = "bslib-page-dashboard",
  title = "我的仪表盘",
  sidebar = sidebar(...),
  ...
)
针对含仪表盘页面的
page_navbar()
将类应用到单个
nav_panel()
容器(不要直接加在
page_navbar()
上),这样只有仪表盘页面会显示灰色背景:
r
page_navbar(
  title = "数据分析平台",
  nav_panel("仪表盘", class = "bslib-page-dashboard",
    layout_column_wrap(...)
  ),
  nav_panel("报告",
    # 不添加dashboard类,使用标准白色背景适合展示文案/报告
    ...
  )
)

Interactive Theming Tools

交互式主题工具

bs_theme_preview()

bs_theme_preview()

Standalone demo app for previewing a theme with many example UI components:
r
bslib::bs_theme_preview()                        # Default theme
bslib::bs_theme_preview(bs_theme(preset = "darkly"))  # Custom theme
Includes the theming UI by default (
with_themer = TRUE
).
独立的演示应用,可预览主题在多种示例UI组件上的效果:
r
bslib::bs_theme_preview()                        # 默认主题
bslib::bs_theme_preview(bs_theme(preset = "darkly"))  # 自定义主题
默认包含主题配置UI(
with_themer = TRUE
)。

run_with_themer()

run_with_themer()

Run an existing Shiny app with the theme editor overlay (instead of
shiny::runApp()
):
r
run_with_themer(shinyApp(ui, server))
run_with_themer("path/to/app")
给现有Shiny应用添加主题编辑器浮层(替代
shiny::runApp()
启动应用):
r
run_with_themer(shinyApp(ui, server))
run_with_themer("path/to/app")

bs_themer()

bs_themer()

Add the theme editor to your own app's server function:
r
server <- function(input, output, session) {
  bs_themer()  # Add during development, remove for production
  # ...
}
All three tools print the resulting
bs_theme()
code to the R console for easy copy-paste. Limitations: Bootstrap 5+ only, Shiny apps and
runtime: shiny
R Markdown only, doesn't affect 3rd-party widgets that don't use
bs_dependency_defer()
.
在你自己的应用服务端函数中添加主题编辑器:
r
server <- function(input, output, session) {
  bs_themer()  # 开发阶段添加,生产环境可移除
  # ...
}
这三个工具都会将生成的
bs_theme()
代码打印到R控制台,方便复制粘贴。限制: 仅支持Bootstrap 5及以上版本,仅适用于Shiny应用和
runtime: shiny
的R Markdown,不影响未使用
bs_dependency_defer()
的第三方组件。

Theme Inspection

主题检测

Retrieve computed Sass variable values:
r
vars <- c("body-bg", "body-color", "primary", "border-radius")
bs_get_variables(bs_theme(), varnames = vars)
bs_get_variables(bs_theme(preset = "darkly"), varnames = vars)
Check contrast (for accessibility):
r
bs_get_contrast(bs_theme(), c("primary", "dark", "light"))
Aim for WCAG AA compliance: 4.5:1 for normal text, 3:1 for large text.
获取计算后的Sass变量值:
r
vars <- c("body-bg", "body-color", "primary", "border-radius")
bs_get_variables(bs_theme(), varnames = vars)
bs_get_variables(bs_theme(preset = "darkly"), varnames = vars)
检查对比度(用于无障碍适配):
r
bs_get_contrast(bs_theme(), c("primary", "dark", "light"))
建议达到WCAG AA标准:普通文本对比度4.5:1,大文本3:1。

Best Practices

最佳实践

  1. Prefer
    bs_theme()
    over custom CSS
    -- variables cascade to all related components automatically
  2. Pin Bootstrap version:
    bs_theme(version = 5)
    prevents breakage if defaults change
  3. Use fallback fonts with
    font_collection()
    to avoid FOIT on slow connections
  4. Test across components: inputs, buttons, cards, navs, plots, tables, modals, toasts, mobile
  5. Check accessibility with
    bs_get_contrast()
    and browser dev tools
  6. Use CSS utility classes for one-off styling instead of custom CSS (see sass-and-css-variables.md)
  7. Organize complex themes in a separate
    theme.R
    :
r
undefined
  1. 优先使用
    bs_theme()
    而非自定义CSS
    ——变量会自动级联到所有相关组件
  2. 固定Bootstrap版本
    bs_theme(version = 5)
    可避免默认值变更导致样式崩溃
  3. 使用
    font_collection()
    添加 fallback 字体
    ,避免网络慢时出现FOIT
  4. 在所有组件上测试:输入框、按钮、卡片、导航、绘图、表格、模态框、Toast提示、移动端
  5. 通过
    bs_get_contrast()
    和浏览器开发者工具检查无障碍适配
  6. 使用CSS工具类实现一次性样式调整,无需编写自定义CSS(参考sass-and-css-variables.md
  7. 复杂主题单独放在
    theme.R
    文件中统一管理
r
undefined

theme.R

theme.R

app_theme <- function() { bs_theme( version = 5, primary = "#2c3e50", base_font = font_google("Lato"), heading_font = font_google("Montserrat", wght = c(400, 700)) ) |> bs_add_rules(sass::sass_file("www/custom.scss")) }
undefined
app_theme <- function() { bs_theme( version = 5, primary = "#2c3e50", base_font = font_google("Lato"), heading_font = font_google("Montserrat", wght = c(400, 700)) ) |> bs_add_rules(sass::sass_file("www/custom.scss")) }
undefined

Reference Files

参考文件

  • sass-and-css-variables.md -- Bootstrap's two-layer variable system, CSS custom properties, utility classes
  • dark-mode.md -- Color modes, dark mode, dynamic theming, component compatibility
  • sass-and-css-variables.md——Bootstrap的双层变量系统、CSS自定义属性、工具类
  • dark-mode.md——色彩模式、深色模式、动态主题、组件兼容性