With the tab_style() method we can target specific cells and apply styles to them. We do this with the combination of the style and location arguments. The style argument requires use of styling classes (e.g., style.fill(color="red")) and the location argument needs to be an expression of the cells we want to target using location targeting classes (e.g., loc.body(columns=<column_name>)). With the available suite of styling classes, here are some of the styles we can apply:
the background color of the cell (style.fill()’s color)
the cell’s text color, font, and size (style.text()’s color, font, and size)
the text style (style.text()’s style), enabling the use of italics or oblique text.
the text weight (style.text()’s weight), allowing the use of thin to bold text (the degree of choice is greater with variable fonts)
the alignment of text (style.text()’s align)
cell borders with the style.borders() class
Parameters
style:CellStyle | list[CellStyle]
The styles to use for the cells at the targeted locations. The style.text(), style.fill(), and style.borders() classes can be used here to more easily generate valid styles.
locations:Loc | list[Loc]
The cell or set of cells to be associated with the style. The loc.body() class can be used here to easily target body cell locations.
The GT object is returned. This is the same object that the method is called on so that we can facilitate method chaining.
Examples
Let’s use a small subset of the exibble dataset to demonstrate how to use tab_style() to target specific cells and apply styles to them. We’ll start by creating the exibble_sm table (a subset of the exibble table) and then use tab_style() to apply a light cyan background color to the cells in the num column for the first two rows of the table. We’ll then apply a larger font size to the cells in the fctr column for the last four rows of the table.
Let’s use exibble once again to create a simple, two-column output table (keeping only the num and currency columns). With the tab_style() method (called thrice), we’ll add style to the values already formatted by fmt_number() and fmt_currency(). In the style argument of the first two tab_style() call, we can define multiple types of styling with the style.fill() and style.text() classes (enclosing these in a list). The cells to be targeted for styling require the use of loc.body(), which is used here with different columns being targeted. For the final tab_style() call, we demonstrate the use of style.borders() class as the style argument, which is employed in conjunction with loc.body() to locate the row to be styled.