Gtk not applying custom style to widgets

Hi there!

I am learning Gtk and gjs. I want to apply custom styling to a button widget but it is not working. Below is my code.

imports.gi.versions.Gtk = "3.0";
const { Gtk, Gdk } = imports.gi;

Gtk.init(null);

const win = new Gtk.Window({
  defaultWidth: 450,
  defaultHeight: 500,
  title: "Styles",
});

const btn = new Gtk.Button({
  label: "Click me",
});

const hBox = new Gtk.Box({
  halign: Gtk.Align.CENTER,
  valign: Gtk.Align.CENTER,
});

hBox.add(btn);

const cssProvider = Gtk.CssProvider.new();
cssProvider.load_from_path("button.css");
const screen = Gdk.Screen.get_default();
Gtk.StyleContext.add_provider_for_screen(
  screen,
  cssProvider,
  Gtk.STYLE_PROVIDER_PRIORITY_USER
);

win.add(hBox);
win.show_all();

win.connect("destroy", () => {
  Gtk.main_quit();
});

Gtk.main();

And the button.css file

GtkButton{
    background-color: yellow;
}

I have read through the answers to How to make buttons different colours in Python GTK3 (using gi)? question on SO and even copied the exact example but it is not working for me on Ubuntu 20.04.

The answers on StackOverflow are terribly out of date. The CSS selector for a GtkButton is not GtkButton, and hasn’t been for more than six years.

The proper CSS selector is button, and it’s part of the class documentation.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.