8. Styling with CSS
Learn how to style your MobileUI app with CSS.
MobileUI XML layout files can be styled with Cascading Style Sheets (CSS) as it can be done with many XML-based languages. For MobileUI's CSS the following rules apply:
- All styling of UI elements is done with separate attributes. There is no
style
attribute for inline CSS. - From an embedded or linked CSS file, you can set the values of all attributes of an element.
- Styles are applied in order of declaration of the
<style>
elements. - Element-local attributes always override styles.
- To address elements, you can use CSS 3 Selectors. Currently, there are no pseudo selectors.
Embedded styles
To write CSS within your layout XML file, add a style
element before the layout declarations like shown below.
<?xml version="1.0" encoding="UTF-8"?>
<Layout xmlns="urn:nevernull:mobileui:layout">
<style> Button { textColor: white; backgroundColor: #6111B1; } .mono { fontFamily: monospace; fontSize: 18; } </style> <LinearLayout height="fill_parent" orientation="vertical" padding="16dp" width="fill_parent">
<TextView class="mono" marginTop="12dp" text="#{greeting}" textHorizontalAlign="center"
width="fill_parent" />
<Button horizontalAlign="center" marginTop="56dp" onClick="#{onOpenUrlClicked()}"
paddingLeft="12dp" paddingRight="12dp" text="Yeah, take me to the candy shop" />
</LinearLayout>
</Layout>
Linked styles
To reference a CSS file, use the href
attribute of the <style>
element in your layout. You can apply more than one CSS file by adding several <style>
elements. The styles are applied in order of declaration. This means, styles can override each other as needed.
<?xml version="1.0" encoding="UTF-8"?>
<Layout xmlns="urn:nevernull:mobileui:layout">
<style href="first.css"/> <style href="second.css"/> <LinearLayout height="fill_parent" orientation="vertical" padding="16dp" width="fill_parent">
<TextView class="mono" marginTop="12dp" text="#{greeting}" textHorizontalAlign="center"
width="fill_parent" />
<Button horizontalAlign="center" marginTop="56dp" onClick="#{onOpenUrlClicked()}"
paddingLeft="12dp" paddingRight="12dp" text="Yeah, take me to the candy shop" />
</LinearLayout>
</Layout>
Using MVEL expressions in referenced CSS files
If you reference CSS files via the href
attribute of the <style>
element, MobileUI currently does not apply MVEL templates within your CSS file to resolve variables.
To solve this, you can use MVEL @include{}
syntax to include the content of the CSS file as body of a <style>
element as shown below:
<style>@include{'main.css'}</style>
In this case, MVEL will resolve variables from orb tags (@{...}
) and more, that appear within the CSS file like in the example below:
.inlineText {
paddingLeft:@{shortDistance}dp;
paddingRight:@{shortDistance}dp;
backgroundColor:@{myMainColor};
}
This is a common way to work with variables for styling in MobileUI.