blob: 3d1b805f1ee2c326c3c29faae01e64c53e0ed86a [file] [log] [blame]
Hao Zhu501fb452017-07-05 14:37:13 -04001#' Put a HTML table into a scrollable box
2#'
3#' @description This function will put a HTML kable object in a fixed-height,
4#' fixed-width or both box and make it scrollable.
5#'
6#' @param kable_input A HTML kable object
7#' @param height A character string indicating the height of the box, e.g. "50px"
8#' @param width A character string indicating the width of the box, e.g. "100px"
Hao Zhu4b0c51e2017-08-01 15:21:07 -04009#' @param box_css CSS text for the box
10#' @param extra_css Extra CSS styles
Hao Zhu501fb452017-07-05 14:37:13 -040011#'
12#' @export
Irene319a5462018-04-17 15:37:39 -070013#'
14#' @examples
15#' \dontrun{
16#' # Specify table size by pixels
17#' kable(cbind(mtcars, mtcars), "html") %>%
18#' kable_styling() %>%
19#' scroll_box(width = "500px", height = "200px")
20#'
21#' # Specify by percent
22#' kable(cbind(mtcars, mtcars), "html") %>%
23#' kable_styling() %>%
24#' scroll_box(width = "100%", height = "200px")
25#' }
26
Hao Zhu4b0c51e2017-08-01 15:21:07 -040027scroll_box <- function(kable_input, height = NULL, width = NULL,
28 box_css = "border: 1px solid #ddd; padding: 5px; ",
29 extra_css = NULL) {
Hao Zhu501fb452017-07-05 14:37:13 -040030 kable_attrs <- attributes(kable_input)
31 out <- as.character(kable_input)
Hao Zhu4b0c51e2017-08-01 15:21:07 -040032 box_styles <- c(box_css, extra_css)
Hao Zhu501fb452017-07-05 14:37:13 -040033 if (!is.null(height)) {
34 box_styles <- c(box_styles,
35 paste0("overflow-y: scroll; height:", height, "; "))
36 }
37 if (!is.null(width)) {
38 box_styles <- c(box_styles,
39 paste0("overflow-x: scroll; width:", width, "; "))
40 }
41 out <- paste0('<div style="', paste(box_styles, collapse = ""), '">',
42 out, '</div>')
43 out <- structure(out, format = "html",
44 class = "knitr_kable")
45 attributes(out) <- kable_attrs
Hao Zhuf2100832018-01-11 16:20:29 -050046 if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
Hao Zhu501fb452017-07-05 14:37:13 -040047 return(out)
48}