Search code examples
javacssgwtlistboxuibinder

Single GWT Listbox won't accept CSS, but overriding all GWT Listboxes works


I am using GWT to work on a web application in which several listboxes are used for various things. I want to change the background color of a specific listbox (to indicate that it's a required field for the user) using a CSS class. This is straightforward enough until the part where I find I am unable to get the listbox to adopt my CSS class at all. I'd like to note that I am using UiBinder and a mix of XML and Java to create and use application controls, and I've disabled Google's Standard theme while I've been trying to get this sorted out. Here's what I've tried in Java code so far:

@UiField
ListBox knownIssuesCombo;
...

public KnownIssuesPanel() {
  ...
  knownIssuesCombo = new ListBox();
  knownIssuesCombo.addStyleName("requiredField"); //This should work!!!
  //knownIssuesCombo.addStyleDependentName("-requiredField");
  //knownIssuesCombo.setStyleName("requiredField", true);
  //knownIssuesCombo.setStyleDependentName("-requiredField", true);
}

And the matching CSS:

.requiredField {
    background-color: Green;
}

.gwt-ListBox-requiredField {
    background-color: Green;
}

I CAN actually change the appearance of all of the listboxes in my application by overriding GWT's CSS like so:

.gwt-Listbox {
    background-color: Green;
}

But I don't want to make ALL of my listboxes green; I just want to affect a single, specific one. Any help or insight into this issue would be greatly appreciated!


Solution

  • Probably a basic specificity issue (your browser dev tools should help you find it); basically you probably have a background-color for .gwt-ListBox that's being defined after (after in the same CSS file, or in a second file loaded after the one that contains: ) the background-color for .requiredField, and because the .gwt-ListBox and .requiredField selectors have the same specificity, the latter one wins.

    Solutions:

    • make sure .requiredField appears/is loaded after .gwt-ListBox
    • or use a selector that is more specific than .gwt-ListBox, e.g. .gwt-ListBox.requiredField
    • or use a dependent style name (addStyleDependentName("required") and a .gwt-ListBox-required selector)

    Note: !important will work but is bad practice (reasons are rooted in accessibility, and user choice (user-specific stylesheets))