File: color.md

package info (click to toggle)
textual 2.1.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,084 kB
  • sloc: python: 85,423; lisp: 1,669; makefile: 101
file content (90 lines) | stat: -rw-r--r-- 1,978 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# Color

The `color` style sets the text color of a widget.

## Syntax

--8<-- "docs/snippets/syntax_block_start.md"
color: (<a href="../../css_types/color">&lt;color&gt;</a> | auto) [<a href="../../css_types/percentage">&lt;percentage&gt;</a>];
--8<-- "docs/snippets/syntax_block_end.md"

The `color` style requires a [`<color>`](../css_types/color.md) followed by an optional [`<percentage>`](../css_types/percentage.md) to specify the color's opacity.

You can also use the special value of `"auto"` in place of a color. This tells Textual to automatically select either white or black text for best contrast against the background.

## Examples

### Basic usage

This example sets a different text color for each of three different widgets.

=== "Output"

    ```{.textual path="docs/examples/styles/color.py"}
    ```

=== "color.py"

    ```python
    --8<-- "docs/examples/styles/color.py"
    ```

=== "color.tcss"

    ```css hl_lines="8 12 16"
    --8<-- "docs/examples/styles/color.tcss"
    ```

### Auto

The next example shows how `auto` chooses between a lighter or a darker text color to increase the contrast and improve readability.

=== "Output"

    ```{.textual path="docs/examples/styles/color_auto.py"}
    ```

=== "color_auto.py"

    ```py
    --8<-- "docs/examples/styles/color_auto.py"
    ```

=== "color_auto.tcss"

    ```css hl_lines="2"
    --8<-- "docs/examples/styles/color_auto.tcss"
    ```

## CSS

```css
/* Blue text */
color: blue;

/* 20% red text */
color: red 20%;

/* RGB color */
color: rgb(100, 120, 200);

/* Automatically choose color with suitable contrast for readability */
color: auto;
```

## Python

You can use the same syntax as CSS, or explicitly set a `Color` object.

```python
# Set blue text
widget.styles.color = "blue"

from textual.color import Color
# Set with a color object
widget.styles.color = Color.parse("pink")
```

## See also

 - [`background`](./background.md) to set the background color in a widget.