source(
  rprojroot::find_package_root_file("vignettes/_common.R")
)

```{scss, echo = FALSE} .section.level2 { margin-top: 3rem; }

```r

Cards are a common organizing unit for modern user interfaces (UI). At their core, they're just rectangular containers with borders and padding. However, when utilized properly to group related information, they help users better digest, engage, and navigate through content. This is why most successful dashboard/UI frameworks make cards a core feature of their component library. This article provides an overview of the API that bslib provides to create Bootstrap cards.

Setup code

To demonstrate that bslib cards work outside of Shiny (i.e., in R Markdown, static HTML, etc), we'll make repeated use of statically rendered htmlwidgets like {plotly} and {leaflet}. Here's some code to create those widgets:

library(bslib)
library(shiny)
library(htmltools)
library(plotly)
library(leaflet)

plotly_widget <- plot_ly(x = diamonds$cut) %>%
  config(displayModeBar = FALSE) %>%
  layout(margin = list(t = 0, b = 0, l = 0, r = 0))

leaflet_widget <- leafletOptions(attributionControl = FALSE) %>%
  leaflet(options = .) %>%
  addTiles()

::: {.callout .callout-note}

Shiny usage

Cards work equally well in Shiny. In the examples below, replace plotly_widget with plotlyOutput() and leaflet_widget with leafletOutput() to adapt them for Shiny server-rendered plots/maps. :::

Hello card()

::: {.row .mt-3} ::: col-md-6 A card() is designed to handle any number of "known" card items (e.g., card_header(), card_body(), etc) as unnamed arguments (i.e., children). As we'll see shortly, card() also has some useful named arguments (e.g., full_screen, height, etc).

At their core, card() and card items are just an HTML div() with a special Bootstrap class, so you can use Bootstrap's utility classes to customize things like colors, text, borders, etc. :::

::: col-md-6

card(
  card_header(
    class = "bg-dark",
    "A header"
  ),
  card_body(
    markdown("Some text with a [link](https://github.com)")
  )
)

::: :::

Implicit card_body()

::: {.row .mt-3} ::: col-md-6 If you find yourself using card_body() without changing any of its defaults, consider dropping it altogether since any direct children of card() that aren't "known" card() items, are wrapped together into an implicit card_body() call.[^1] For example, the code to the right generates HTML that is identical to the previous example: :::

[^1]: If you want to customize this behavior, you can provide a function to wrapper argument (or set it to NULL to avoid wrapping the non card items in a container).

::: col-md-6

card(
  card_header(
    class = "bg-dark",
    "A header"
  ),
  markdown("Some text with a [link](https://github.com).")
)

::: :::

Restricting growth

::: {.row .mt-3} ::: col-md-6 By default, a card()'s size grows to accommodate the size of its contents. Thus, if a card_body() contains a large amount of text, tables, etc., you may want to specify a height or max_height. That said, when laying out multiple cards, it's likely best not to specify height on the card(), and instead, let the layout determine the height layout_column_wrap().

Although scrolling is convenient for reducing the amount of space required to park lots of content, it can also be a nuisance to the user. To help reduce the need for scrolling, consider pairing scrolling with full_screen = TRUE (which adds an icon to expand the card's size to the browser window). Notice how, when the card is expanded to full-screen, max_height/height won't effect the full-screen size of the card. :::

::: col-md-6

card(
  max_height = 250,
  full_screen = TRUE,
  card_header(
    "A long, scrolling, description"
  ),
  lorem::ipsum(paragraphs = 3, sentences = 5)
)

::: :::

Filling outputs

::: {.row .mt-3} ::: col-md-6 A card()'s default behavior is optimized for facilitating filling layouts. More specifically, if a fill item (e.g., plotly_widget), appears as a direct child of a card_body(), it resizes to fit the card()s specified height. This means, by specifying height = 250 we've effectively shrunk the plot's height from its default of 400 down to about 200 pixels. And, when expanded to full_screen, the plot grows to match the card()'s new size. :::

::: col-md-6

card(
  height = 250,
  full_screen = TRUE,
  card_header("A filling plot"),
  card_body(plotly_widget)
)

::: :::

::: {.row .mt-5} ::: col-md-6 Most htmlwidgets (e.g., plotly, leaflet, etc) and some other Shiny output bindings (e.g, plotOutput(), imageOutput(), etc) are fill items by default, so this behavior "just works" in those scenarios. And, in some of these situations, it's helpful to remove card_body()'s padding, which can be done via spacing & alignment utility classes. :::

::: col-md-6

card(
  height = 275,
  full_screen = TRUE,
  card_header("A filling map"),
  card_body(
    class = "p-0",
    leaflet_widget
  ),
  card_footer(
    class = "fs-6",
    "Copyright 2023 RStudio, PBC"
  )
)

::: :::

::: {.row .mt-5} ::: col-md-6 Fill item(s) aren't limited in how much they grow and shrink, which can be problematic when a card becomes very small. To work around this, consider adding a min_height on the card_body() container. For example, try using the handle on the lower-right portion of this card example to make the card taller/smaller.

This interactive example is a bit contrived in that we're using CSS resize to demonstrate how to make plots that don't shrink beyond a certain point, but this concept becomes quite useful when implementing page-level filling layouts (i.e., page_fillable()) with multiple cards. :::

::: col-md-6

card(
  height = 300,
  style = "resize:vertical;",
  card_header("Plots that grow but don't shrink"),
  card_body(
    min_height = 250,
    plotly_widget,
    plotly_widget
  )
)

::: :::

::: {.callout .callout-warning}

Troubleshooting fill

As you'll learn more about in filling layouts, a fill item loses its ability to fill when wrapped in additional UI element that isn't a fillable container. To fix the situation, use as_fill_carrier() to allow the additional element to carry the potential to fill from the card_body() down to the fill item. :::

Multiple card_body()

A card() can have multiple card_body()s, which is especially useful for:

  1. Combining both resizable and non-resizable contents (i.e., fill items and non-fill).
  2. Allowing each card_body() to have their own styling (via inline styles and/or utility classes) and resizing limits (e.g., min_height).

For example, when pairing filling output with scrolling content, you may want min_height on the filling output since the scrolling content will force it to shrink:

::: {.row .mt-3} ::: col-md-6

card(
  height = 375,
  full_screen = TRUE,
  card_header(
    "Filling plot, scrolling description"
  ),
  card_body(
    min_height = 200,
    plotly_widget
  ),
  card_body(
    class = "lead container",
    lorem::ipsum(paragraphs = 10, sentences = 5)
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

::: {.row .mt-5}

Also, when the content has a fixed size, and should not be allowed to scroll, set fill = FALSE:

::: col-md-6

card(
  height = 350,
  full_screen = TRUE,
  card_header(
    "Filling plot, short description"
  ),
  plotly_widget,
  card_body(
    fill = FALSE, gap = 0,
    card_title("A subtitle"),
    p(class = "text-muted", "And a caption")
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

Multiple columns

As you'll learn in column-based layouts, layout_column_wrap() is great for multi-column layouts that are responsive and accommodate for filling output. Here we have an equal-width 2-column layout using width = 1/2, but it's also possible to have varying column widths.

::: row ::: col-md-6

card(
  height = 350,
  full_screen = TRUE,
  card_header("A multi-column filling layout"),
  card_body(
    min_height = 200,
    layout_column_wrap(
      width = 1/2,
      plotOutput("p1"),
      plotOutput("p2")
    )
  ),
  lorem::ipsum(paragraphs = 3, sentences = 5)
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

Multiple cards

layout_column_wrap() is especially nice for laying out multiple cards since each card in a particular row will have the same height (by default). Learn more in column-based layouts.

layout_column_wrap(
  width = 1/2,
  height = 300,
  card(full_screen = TRUE, card_header("A filling plot"), plotly_widget),
  card(full_screen = TRUE, card_header("A filling map"), card_body(class = "p-0", leaflet_widget))
)

Multiple tabs

navset_card_tab() and navset_card_pill() make it possible to create cards with multiple tabs or pills. These functions have the same full_screen capabilities as normal card()s as well some other options like title (since there is no natural place for a card_header() to be used). Note that, each nav_panel() object is similar to a card(). That is, if the direct children aren't already card items (e.g., card_title()), they get implicitly wrapped in a card_body().

::: {.row .mt-3} ::: col-md-6

library(leaflet)
navset_card_tab(
  height = 450,
  full_screen = TRUE,
  title = "HTML Widgets",
  nav_panel(
    "Plotly",
    card_title("A plotly plot"),
    plotly_widget
  ),
  nav_panel(
    "Leaflet",
    card_title("A leaflet plot"),
    leaflet_widget
  ),
  nav_panel(
    shiny::icon("circle-info"),
    markdown("Learn more about [htmlwidgets](http://www.htmlwidgets.org/)")
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

Sidebars

As you'll learn more about in sidebar layouts, layout_sidebar() just works when placed inside in a card(). In this case, if you want fill items (e.g., plotly_widget) to still fill the card like we've seen before, you'll need to set fillable = TRUE in layout_sidebar().

card(
  height = 300,
  full_screen = TRUE,
  card_header("A sidebar layout inside a card"),
  layout_sidebar(
    fillable = TRUE,
    sidebar = sidebar(
      actionButton("btn", "A button")
    ),
    plotly_widget
  )
)

Static images

card_image() makes it easy to embed static (i.e., pre-generated) images into a card. Provide a URL to href to make it clickable. In the case of multiple card_image()s, consider laying them out in multiple cards with layout_column_wrap() to produce a grid of clickable thumbnails.

::: row ::: col-md-6

card(
  height = 300,
  full_screen = TRUE,
  card_image(
    file = "shiny-hex.svg",
    href = "https://github.com/rstudio/shiny"
  ),
  card_body(
    fill = FALSE,
    card_title("Shiny for R"),
    p(
      class = "fw-light text-muted",
      "Brought to you by RStudio."
    )
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

Flexbox

::: {.row .mt-3}

Both card() and card_body() default to fillable = TRUE (that is, they are CSS flexbox containers), which works wonders for facilitating filling outputs, but it also leads to surprising behavior with inline tags (e.g., actionButton(), span(), strings, etc). Specifically, each inline tag is placed on a new line, but in a "normal" layout flow (fillable = FALSE), inline tags render inline.

::: col-md-6

card(
  card_body(
    fillable = TRUE,
    "Here's some", tags$i("inline"), "text",
    actionButton("btn1", "A button")
  ),
  card_body(
    fillable = FALSE,
    "Here's some", tags$i("inline"), "text",
    actionButton("btn2", "A button")
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

::: {.row .mt-3}

That said, sometimes working in a flexbox layout is quite useful, even when working with inline tags. Here we leverage flexbox's gap property to control the spacing between a plot, a (full-width) button, and paragraph. Note that, by using markdown() for the paragraph, it wraps the results in a <p> tag, which means the contents of the paragraph are not longer subject to flexbox layout. If we wanted, we could do something similar to render the actionButton() inline by wrapping it in a div().

::: col-md-6

card(
  height = 325, full_screen = TRUE,
  card_header("A plot with an action links"),
  card_body(
    class = "gap-2 container",
    plotly_widget,
    actionButton(
      "go_btn", "Action button",
      class = "btn-primary rounded-0"
    ),
    markdown("Here's a _simple_ [hyperlink](https://www.google.com/).")
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

::: {.row .mt-3} In addition to gap, flexbox has really nice ways of handling otherwise difficult spacing and alignment issues. And, thanks to Bootstrap's flex utility classes, we can easily opt-in and customize defaults.

::: col-md-6

card(
  height = 300, full_screen = TRUE,
  card_header(
    class = "d-flex justify-content-between",
    "Centered plot",
    checkboxInput("check", " Check me", TRUE)
  ),
  card_body(
    class = "align-items-center",
    plotOutput("id", width = "75%")
  )
)

:::

::: {.col-md-6 .mt-auto .mb-auto}


::: :::

Shiny

::: row ::: col-md-6 Since this article is statically rendered, the examples here use statically rendered content/widgets, but the same card() functionality works for dynamically rendered content via Shiny (e.g., plotOutput(), plotlyOutput(), etc).

An additional benefit that comes with using shiny is the ability to use getCurrentOutputInfo() to render new/different content when the output container becomes large enough, which is particularly useful with card(full_screen = T, ...). For example, you may want additional captions/labels when a plot is large, additional controls on a table, etc (see the value boxes article for a clever use of this). :::

::: col-md-6

# UI logic
ui <- page_fluid(
  card(
    max_height = 200,
    full_screen = TRUE,
    card_header("A dynamically rendered plot"),
    plotOutput("plot_id")
  )
)

# Server logic
server <- function(input, output, session) {
  output$plot_id <- renderPlot({
    info <- getCurrentOutputInfo()
    if (info$height() > 600) {
      # code for "large" plot
    } else {
      # code for "small" plot
    }
  })
}

shinyApp(ui, server)

::: :::

Appendix

The following CSS is used to give plotOutput() a background color; it's necessary here because this documentation page is not actually hooked up to a Shiny app, so we can't show a real plot.

.shiny-plot-output {
  background-color: #216B7288;
  height: 400px;
  width: 100%;
}


rstudio/bootstraplib documentation built on June 17, 2024, 9:42 a.m.