Swap background/foreground colors of gtk widget

Hi everyone,

is there css way (or any other one) to swap background/foreground colors of some widget?

p.s. with css “filter: invert(100%);” foreground color (text color) is swapped, but I cannot find out how to swap correspondent background color

I don’t know how to invert unknown colors. But you can use named colors.

/* style.css */

@define-color mywidget_fg_color #000;
@define-color mywidget_bg_color #fff;

.mywidget {
  color: @mywidget_fg_color;
  background-color: @mywidget_bg_color;
}
/* In your Application's "startup" function (or signal handler) */

my_application_startup(GtkApplication *self) {
    GdkDisplay *display = gdk_display_get_default ();
    GtkCssProvider *css_provider = gtk_css_provider_new ();

    gtk_style_context_add_provider_for_display (
        display,
        GTK_STYLE_PROVIDER(css_provider),
        GTK_STYLE_PROVIDER_PRIORITY_APPLICATION
    );
}

Then, as long as you keep a reference to css_provider, you can redefine the colors anywhere in your code as you see fit. They will take effect immediately.

gtk_css_provider_load_from_string (css_provider,
    "@define-color mywidget_fg_color #fff;\n"
    "@define-color mywidget_bg_color #000;\n"
);

However, if you want to do this in order to support dark mode, and you are using LibAdwaita, you can simply put CSS (redefinitions of colors) in {resource-base-path}/style-dark.css and they will only take effect in dark mode. See Adw.Application#automatic-resources for more info.

Thank you for reply, that’s the case when “mywidget_bg_color” isn’t known beforehand. Yes, had it known, it could be inverted and set wherever it’s applicable. With foreground it’s possible with css “filter: invert(100%);", but not with background (or I’m missed smth obvious).

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