在Shiny应用中实现图标与文本同行显示的问题
The issue happens because renderText outputs a block-level <div> element by default, which takes up full width and pushes content below it. Additionally, the default column layout doesn’t align elements vertically to stay on the same line. Here are two simple fixes:
Solution 1: Use Inline Text with tags$span
Replace renderText with renderUI using tags$span (an inline element) and place the icon and text within the same column:
## app.R ## library(shiny) library(shinydashboard) library(shinydashboardPlus) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( box(title = "Selections", column(6, fluidRow( column(12, tagList( icon("calendar"), uiOutput("date1date2") )))), column(6, fluidRow( column(12, tagList( icon("bars"), uiOutput("prdttx") ))) ) ) ) ) server <- function(input, output) { output$date1date2 <- renderUI({ tags$span("fdsfsdfffs") }) output$prdttx <- renderUI({ tags$span("fdsfsdfffs") }) } shinyApp(ui, server)
Solution 2: Flexbox Alignment via CSS
Add flexbox styling to the fluidRow to vertically align the icon and text columns:
## app.R ## library(shiny) library(shinydashboard) library(shinydashboardPlus) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( box(title = "Selections", column(6, fluidRow(style = "display: flex; align-items: center;", column(1, icon("calendar")), column(11, uiOutput("date1date2")))), column(6, fluidRow(style = "display: flex; align-items: center;", column(1, icon("bars")), column(11, uiOutput("prdttx")))) ) ) ) server <- function(input, output) { output$date1date2 <- renderText({ "fdsfsdfffs" }) output$prdttx <- renderText({ "fdsfsdfffs" }) } shinyApp(ui, server)
Both solutions will render the icon and text on the same line. Solution 1 converts the text to an inline element, while Solution 2 uses CSS flexbox to align existing block elements vertically.
内容的提问来源于stack exchange,提问作者firmo23

