[Howto] GTK3 with CSS (minimal example)

posted in: computer | 0

It is a working example for a button, which changes its color while mouse-over.

gtk-version:   3.24.12-1

note:  the css-property “background-image: none” is sometimes mandatory, because the default theme prevents displaying the css-defined background-color. The workaround is to set the background-image to none.

filename: test.c

#include <gtk/gtk.h>

int main(int argc, char *argv[]){
  gtk_init(&argc, &argv);

  GtkWidget       *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  GtkWidget       *button = gtk_button_new_with_label("Button");
  GtkCssProvider  *cssProvider = gtk_css_provider_new();

  gtk_css_provider_load_from_path(cssProvider, "test.css", NULL);
  gtk_style_context_add_provider(gtk_widget_get_style_context(button), GTK_STYLE_PROVIDER(cssProvider), GTK_STYLE_PROVIDER_PRIORITY_USER);
  
  gtk_container_add(GTK_CONTAINER(window), button);
  gtk_widget_show_all(window);

  gtk_main();
}

filename: test.css

button {
    color: red;
    background-color: cyan;
    background-image: none;
}


button:hover {
    color: white;
    background-color: black;
}