Skip to contents

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()

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()

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.

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

Some text with a link

Implicit card_body()

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:

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

Some text with a link.

Restricting growth

By default, a card()’s size grows to accommodate the size of it’s 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.

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

Ipsum vestibulum neque lacus class nec condimentum tristique. Urna platea nisl viverra cum euismod mattis montes ridiculus cras. Dapibus torquent nunc blandit ridiculus, ornare ultricies natoque nisi habitasse vel? Ridiculus mi suspendisse aliquam hendrerit erat odio nunc ultrices. Commodo molestie interdum dapibus proin per.

Lorem rhoncus sollicitudin, velit vel porta, volutpat hendrerit dui suspendisse curae. Sodales montes sapien, neque, varius hac metus auctor cubilia pharetra? Turpis sodales sed, auctor nunc dis inceptos hac interdum ultricies. Neque gravida, odio, cras sed laoreet nulla tortor; maecenas proin sollicitudin. Diam commodo et potenti massa risus netus accumsan.

Consectetur erat magna lacinia gravida; porttitor mollis etiam. Ligula dictum in platea aliquet ad. Cubilia imperdiet consequat sagittis sagittis euismod faucibus vulputate blandit. Integer venenatis mattis, vitae quam class curabitur etiam erat consequat. Scelerisque faucibus sollicitudin nascetur a elementum litora lacus imperdiet, mus urna mollis, convallis duis vivamus, metus nullam libero laoreet?

Filling outputs

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.

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

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.

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"
  )
)
A filling map

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.

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