Does Unity UI Toolkit support CSS media queries?

996 Views Asked by At

I would like to override the alignment for elements in my UI on small screens. I've added the following code to the style sheet, but it is not applied to my canvas in UI Builder and does not show up in the USS preview within UI Builder.

@media screen and (max-width:550px) {
  .section {
    justify-content: flex-start;
  }
}

The tutorials I have found related to responsive UI are using the default Unity UI package, not UI Toolkit. I'm having a hard time figuring out how to do this. The images below show the problem.


Uses space-around alignment on any screen wide enough for both sections:

wide screen uses space-around

On a small screen, the sections should be aligned to the left side with flex-start. Instead, the container still using space-around with wrapping, so the sections are off-center:

small screen, not properly aligned

Any help is appreciated! Thanks for your time.

2

There are 2 best solutions below

0
cfaz On BEST ANSWER

The answer is no, The USS in UI toolkit is a custom implementation meant to look like (but not be compatible with) CSS and only implements a handful of selectors and properties.

Custom selectors and media queries are not supported

I think your best bet here is to check for the condition in a script and apply a custom Selector Class to the element if they meet your requirements

1
FokeyJoe On

Just to complement cfaz's answer by showing a simple example of how you might implement a media query system of your own in Unity with UIToolkit.

Add the MonoBehaviour below to a GameObject. Set the UIDocument to the one you want to be aware of screen size in the inspector. Change UpdateBreakpoint() to your hearts' desire. In your USS, use a selector declaration style like

.my-font { font-size: 16px; }
.hi-res .my-font { font-size: 32px }
public class Breakpoints : MonoBehaviour {
    [SerializeField] private UIDocument _uiDocument;

    private int width, height;

    void UpdateBreakpoint() {
        VisualElement root = _uiDocument.rootVisualElement;

        if (height > 640) {
            root.AddToClassList("hi-res");
            root.RemoveFromClassList("lo-res");
        } else {
            root.AddToClassList("lo-res");
            root.RemoveFromClassList("hi-res");
        }
    }

    void Start() {
        UpdateRes();
        UpdateBreakpoint();
    }

    void Update() {
        if (HasResChanged()) {
            UpdateRes();
            UpdateBreakpoint();
        }
    }

    private bool HasResChanged() {
        return (Screen.width != width) || (Screen.height != height);
    }

    private void UpdateRes() {
        width = Screen.width;
        height = Screen.height;
    }
}