为了使各项井井有条,UI 工具包已采用 BEM 作为元素的样式设置方法。虽然并非必须使用 BEM,但是建议采用。
BEM 表示块元素修饰符。BEM 是一个简单的系统,有助于编写结构化、明确、易于维护的选择器。通过 BEM 可以向元素分配类,然后将这些类用作样式表中的选择器。
BEM 类最多包含三个组件:
menu
、button
、list-view
menu__item
、button__icon
或 list-view__item
menu--disabled
、menu__item--disabled
、button--small
或 list-view__item--selected
。每个名称部分可能由拉丁字母、数字和短划线组成。每个名称部分用双下划线 __
或双短划线 --
连接起来。
以下示例显示了菜单的 XML 代码:
<VisualElement class="menu">
<Label class="menu__item" text="Banana" />
<Label class="menu__item" text="Apple" />
<Label class="menu__item menu__item--disabled" text="Orange" />
</VisualElement>
由于每个元素都配有描述其作用和外观的类,因此您可以仅使用一个类名来编写大多数选择器:
.menu {
}
.menu__item {
}
.menu__item--disabled {
}
应该能够使用单个类名来设置元素的样式。但是在某些情况下,可能需要使用复杂的选择器。例如,元素的样式取决于其块的修饰符时,可以使用复杂的选择器:
.button {
}
.button__icon {
}
.button--small {
}
.button--small .button__icon {
}
注意不要指定长选择器。长选择器可能表示 UI 的图形设计不一致。还应该避免在 BEM 选择器中使用类型名称(Button
、Label
)或元素名称 (#my-button
)。
VisualElement
支持 BEMUI 工具包遵循 BEM。每个视觉元素都附有必要的类名。例如,所有 TextElement
具有 unity-text-element
类。从 TextElement
派生的 Button
的每个实例在类列表中都填充有 unity-button
和 unity-text-element
类。
如果从 VisualElement
或其某个后代派生新元素,请遵循以下准则以确保元素易于使用 BEM 方法进行样式设置:
AddToClassList()
,将相关 USS 类添加到元素实例。my-block__first-child
、my-block__other-child
。Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.