Cascading Style Sheets

Applications can be styled using Cascading Style Sheets (CSS). This approach is often quicker and more convenient than trying to fine tune the appearance of widgets using code.

In this example we apply a single style sheet in a very simple way.

Loading the Style Sheet

Style sheets may be loaded from the user’s system, either from a standard style sheet stored in a default location, or from one installed with the application. Alternatively, they can be supplied with the application in a resource bundle, as in this example.

In this example, the application creates an instance of the Gtk.CssProvider class in its do_startup method, and loads the style.css style sheet from the resource bundle that has already been loaded:

css = Gtk.CssProvider()

Once loaded into it, the CssProvider instance can be used to style any widget with suitable CSS nodes.

Applying the Style Sheet

The CssProvider instance can be used to style any individual widget by calling its Gtk.Widget.get_style_context method and applying the provider to it. Another approach is to apply the style sheet to the entire application:

    Gdk.Screen.get_default(), css, Gtk.STYLE_PROVIDER_PRIORITY_USER

Care must be taken to avoid changing the default appearance of widgets provided by the system theme. To ensure that only certain widgets are changed, we give those widgets names by setting their name properties. We define rules in the CSS file to only modify those named widgets, as shown in this snippet:

#day {
    background-color: black;
    color: white;
    font-size: 1.5em;
    font-weight: bold

In this case, any widget whose name property has the value day is styled according to this rule, but other unnamed widgets have the default style. Because more than one widget can share the same value for the same property, there can be multiple widgets whose name property is also day, and this allows us to style all the labels showing the days of the week consistently.

Consistently styled labels for days of the week

Consistently styled labels for days of the week

Rules can be written to restrict styling to specific types of widgets, as in the following which is only applied to the header of any Gtk.TreeView widget whose name property is places:

treeview#places header
    font-size: 1.25em

Care must be taken to avoid applying too many rules to the widgets in your application, or applying rules too generally, as this can make it difficult to adjust their appearance later without causing side effects.

Further Reading

The GTK CSS Overview and GTK CSS Properties documents on the GNOME developer site are useful for determining which parts of the standard widgets can be styled, and what changes they support.