rshinymedia-queriesnavbarbslib

How to let a bslib navbar collapse at another Bootstrap breakpoint?


In my shiny app, I need to change the default bslib behavior of collapsing the navbar at 992px by setting it at 1200px. Here's a reprex:

library(shiny)
library(bslib)

# Reproducible example UI
app_ui <- function(request) {
  shiny::tagList(

    # I expected this CSS code to work but it doesn't :

    tags$style(HTML("
    /* Custom CSS to expand navbar at xl breakpoint rather than 992 default */
    @media (min-width: 1200px) {
      #nav.navbar-expand-xl .navbar-collapse {
        display: flex !important; 
        flex-basis: auto !important;
        -webkit-flex-basis: auto !important;
      }
    }
  ")),

    bslib::page_navbar(
      id = "nav",
      fillable = TRUE,
      theme = bs_theme(version = 5),  # Using default Bootstrap theme for simplicity
      
      bslib::nav_panel("I will collapse at 992px by default", "..."),
      
      bslib::nav_spacer(),
      
      bslib::nav_item(
        
      )
    )
  )
}

server <- function(input, output, session) {}

shinyApp(app_ui, server)

My attempt to fix this is by writing CSS code (see tags$style at the top of the app) but it makes no effect.

How can I specifically target this navbar id ('nav') and make it collapse at 1200px and below, rather than the default 992px and below ? The only lead I found is in this post, but this suggests overriding the breakpoints of the whole app, which is not desired in my case (complex app already refering to existing breakpoints).


Solution

  • Collapsing at 1200px and below corresponds to the xl breakpoint. Hence, the CSS should already be suitable without further modifications and you could change the navbar class to navbar-expand-xl.

    This can be achieved by passing the class into navbar_options() (requires bslib >= 0.90):

    library(shiny)
    library(bslib)
    
    app_ui <- page_navbar(
      navbar_options = list(
        class = "navbar-expand-xl"
      ),
      nav_panel("I will collapse at 1200px", "...")
    )
    
    shinyApp(app_ui, \(...){})
    

    In bslib < 0.90, one could use htmltools::tagAppendAttributes():

    page_navbar(
      ...
    ) |>
      tagAppendAttributes(.cssSelector = "nav", class = "navbar-expand-xl")