You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用bslib/Sass变量将R Shiny中所有标签设置为加粗

如何通过bs_theme()的Sass变量将Shiny应用的标签设为加粗?

你编写的Shiny应用代码如下:

library(shiny)
library(bslib)

ui <- fluidPage(
  
  theme = bs_theme(version = 5, 
                   bootswatch = "litera",
                   base_font = "Arial", 
                   heading_font = "Arial",
                   font_scale = 1),
  
  sidebarLayout(
    
    # ui sidebarPanel ---------------------------------------------------------------
    sidebarPanel(
      br(),
      textInput("txt_input", 
                label = "Enter text:"),
      br(),
      selectInput("select", 
                  label = "Select choice:", 
                  choices = c("One", "Two", "Three"))
    ),
    
    mainPanel(
      br(),
      htmlOutput("result")
    )
  )
)

server <- function(input, output, session) {
  observe({
    output$result <- renderUI(
      HTML(sprintf("  Selected choice: %s", input$select))
    )
  })
}
shinyApp(ui, server)

你希望通过bs_theme()的Sass变量将所有标签设为加粗,但找不到对应变量。实际上Bootstrap 5(包括litera主题)并没有预设控制表单标签字体粗细的Sass变量,不过可以通过bs_add_rules()向主题添加自定义规则来实现需求:

解决方案

修改theme参数,在bs_theme()后链式调用bs_add_rules(),针对Shiny表单标签对应的.form-label类设置加粗样式:

library(shiny)
library(bslib)

ui <- fluidPage(
  
  theme = bs_theme(version = 5, 
                   bootswatch = "litera",
                   base_font = "Arial", 
                   heading_font = "Arial",
                   font_scale = 1) %>%
    # 添加自定义规则,让所有表单标签加粗
    bs_add_rules(".form-label { font-weight: bold; }"),
  
  sidebarLayout(
    
    sidebarPanel(
      br(),
      textInput("txt_input", 
                label = "Enter text:"),
      br(),
      selectInput("select", 
                  label = "Select choice:", 
                  choices = c("One", "Two", "Three"))
    ),
    
    mainPanel(
      br(),
      htmlOutput("result")
    )
  )
)

server <- function(input, output, session) {
  observe({
    output$result <- renderUI(
      HTML(sprintf("  Selected choice: %s", input$select))
    )
  })
}
shinyApp(ui, server)

说明

Shiny生成的表单输入标签会自动套用Bootstrap 5的.form-label类,通过给这个类设置font-weight: bold,就能全局统一将所有输入标签设为加粗样式。如果需要更精准的范围控制(比如仅侧边栏内的标签),可以调整CSS选择器,例如:.sidebarPanel .form-label { font-weight: bold; }。

内容的提问来源于stack exchange,提问作者Gerben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:39