Telerik blogs

Though Cascading Style Sheets are often used to style webpages, we can now use CSS to theme our .NET MAUI mobile and desktop apps. Let’s learn how!

Applying styles to our applications helps us save code by allowing us to reuse different properties in one or more than one visual element without the need to repeat it. It also allows us to better maintain the visual identity (or branding) of our apps. In .NET MAUI, we can apply these styles with XAML, and also with CSS!

In this article we will go through all the necessary steps for you to learn how to add styles with CSS to your .NET MAUI applications!

What Is CSS?

Before going into the material, let’s refresh with some important points.

Cascading Style Sheets (CSS) allow you to define multiple visual properties of interface elements in a reusable way. CSS is a language used for the composition and structuring of webpages. It is a list of rules to define the styles of your application, generally used for web applications, but today we will learn how to integrate CSS into mobile and desktop applications with .NET MAUI.

Table of Contents

The explanation of this article will be based on the following topic structure:

Let’s see each one of them in detail.

πŸ—’ Consuming a Style Sheet

The first thing you should have at hand is your .NET MAUI application (you can create a new one or use an existing one). Then apply the following instructions:

Step 1: Create Your CSS File in the Resources Folder

Go to Resources ➑ Styles folder and inside this one, create your .css file. (For this example, my file will be called StyleCSS.css.)

πŸ“‹ You can add it to any other folder. However, to maintain a better organization and structure, Resources ➑ Styles is recommended.

^contentpage { 
  background-color: lightpink; 
}

stacklayout { 
  -maui-spacing: 6;
  margin: 40; 
} 

grid { 
  row-gap: 6; 
  column-gap: 6; 
}

stacklayout>image { 
  height: 200; 
  width: 200; 
}

Step 2: Set the Build Action to the CSS File

Go to Resources ➑ Styles ➑ Your CSS File-➑ Right Click ➑ Build Action ➑ MauiCSS. As you will see below:

1. Open Resources folder, 2. Open Styles folder, 3. Right click in CSS file, 4. Click in Build Action, 5. Set MauiCss value

❗ The CSS file will fail to load if its Build Action is not set to MauiCss.

πŸ“’ Loading a Style Sheet in XAML

Once you have done the previous step, now we are going to load this CSS sheet in our app as follows:

Add the StyleSheet Class

Let’s add the StyleSheet class which allows us to load and parse the style sheet. Go to your SamplePage.xaml file and inside the <ContentPage.Resources> tags, add the following:

<ContentPage.Resources>
   <StyleSheet Source="Resources/Styles/StyleCSS.css" />
</ContentPage.Resources>

πŸ“ƒ Remember that “StyleCSS.css” is the name of my CSS file sample. If yours has another name, you must replace it.

Another option to do it is adding a CDATA section:

<ContentPage ...>
   <ContentPage.Resources>
    <StyleSheet>
     <![CDATA[ 
     ^contentpage {
       background-color: lightpink;
       }
      ]]> 
    </StyleSheet> 
  </ContentPage.Resources> 
... 
</ContentPage>

πŸ“’ Loading a Style Sheet in C#

A CSS document can be loaded from a StringReader to later be added to a ResourceDictionary:

using Microsoft.Maui.Controls.StyleSheets;
public partial class MyPage : ContentPage
{
  public MyPage()
  { 
    InitializeComponent(); 
    using (var reader = new StringReader("^contentpage { background-color: lightpink; }")) 
    { 
     this.Resources.Add(StyleSheet.FromReader(reader)); 
    } 
   } 
}

Understanding Child Style Sheet Behavior

Child style sheets override parent style sheets if the same properties are set.

Therefore, for the occasions in which properties are repeated, the following precedence rules are followed:

  • A style defined in the application resources will be overridden by a style defined in the page resources.
  • A style defined in page resources will be overwritten by a style defined in the control resources.
  • A style defined in the app resources will be overwritten by a style defined in the control resources.

What Are Selector Elements?

Selectors are responsible for determining the element to which the style will be applied. To be able to apply the styles, it’s a priority to know the selectors in CSS. You can use the same selectors as CSS in .NET MAUI!

Exploring Selector Types

There are different selector types. Below we will see their definitions and examples of each one:

Tag or Type Selectors

These allow you to indicate the name or the tag to which the CSS properties will be assigned.

Let’s see an example:

This example selects all elements of type StackLayout and sets the Margin property to 50 as its value.

Selector: Element, Example:StackLayout, Description:Select all elements of type StackLayout and set its Margin property with 50 as value., Code example: stacklayout { margin: 50; }

⚠ The element selector does not identify subclasses of the specified type.

Base Class Selectors

These allow you to indicate the elements in the visual tree that can be selected by base class with ^base selector.

Let’s see an example:

This example is selecting all elements with ContentPage as the base class (including ContentPage itself) and sets it to a Green background color.

Selector: ^base, Example:^contentpage, Description:Selects all elements with ContentPage as the base class and sets Green as a background color., Code example: ^contentpage { background-color: green; }

Important to keep in mind:

  • It does not distinguish between upper and lower case.
  • The ^base selector is specific to .NET MAUI and is not part of the CSS specification.

ID or Name Selectors

These allow you to select an element by its ID or name. Identifies the element whose StyleId property is set to an element. In case the StyleId property is not established, it will take the data from the x:Name property of the element.

Let’s see an example:

Imagine you already have a button named SendButton.

<Button x:Name="SendButton"
  Text="Send"
  Background="Pink"/>

Now, let’s continue with the CSS styling:

A blue background was added to elements with the id #SendButton.

Selector: #id, Example: #SendButton, Description: Adds a blue background to elements with #SendButton ID., Code example: #SendButton { background-color:blue; }

Class Selectors

These allow you to select an element by class name. A CSS class can be assigned to a XAML element by setting the element’s StyleClass property to the name of the CSS class.

Let’s see an example:

Imagine you already have two Buttons with some assigned classes:

<Button StyleClass="resumenName" />
<Button StyleClass="resumenLastName" />

Now, let’s continue with the CSS styling:

Here we apply different properties to the resumeName and resumeLastName classes which are contained in two buttons.

Selector: .class, Example: .resumeName & .resumeLastName, Description: Applies properties to the resumeName and resumeLastName classes., Code example: resumenName { font-style: bold; font-size: 24; .resumenLastName { text-align: center; font-style: italic; }

Child Element Selectors

These allow selecting the child elements in the visual tree.

Let’s see an example:

Imagine you already have an image inside a StackLayout:

<StackLayout>
   <Image Source="dotnet_bot"/
</StackLayout>

Now, let’s continue with the CSS styling:

The example sets the height and width of the images within the StackLayouts.

Selector: element element,  Example: stacklayout image, Description: Sets the height and width of images within stacklayouts., Code example: stacklayout image { height: 60; width: 60; }

The selected element does not have to be direct—it can be secondary. It may happen that the element is an ancestor.

In case you only want to refer to the direct element, you can do it using the “>” sign, as follows:

Selector: element{greater than symbol}element,  Example: stacklayout{greater than symbol}image, Description: Sets the height and width of images within stacklayouts., Code example: stacklayout{greater than symbol}image { height: 60; width: 60; }

Other Types of Selectors

  • Element + Element: It allows you to indicate the direct elements that you want to select after an indicated main one. In this case the example selects all the Entry directly after the Label.

Selector: element element,  Example: stacklayout image, Description: Sets the height and width of images within stacklayouts., Code example: stacklayout image { height: 60; width: 60; }

  • Element ~ Element: It allows you to indicate the preceded elements that you want to select before an indicated one. In this case the example selects all Entry elements preceded by a Label.

Selector: element~element,  Example: label~entry, Description: Selects all Entry elements preceded by a Label., Code example: label~entry { font-size: 24; }

πŸ“‹ Selectors can be combined without limitation. For example:

StackLayout>ContentView>label.email.

πŸ“ Property Reference

The following CSS properties are supported by .NET MAUI:

πŸ”§ PropertyπŸ“ Applies to

  • align-content
  • align-items
  • flex-direction
  • justify-content
  • position
FlexLayout

  • align-self
  • background-color
  • direction
  • flex-basis
  • flex-grow
  • flex-shrink
  • flex-wrap
  • height
  • min-height
  • min-width
  • opacity
  • order
  • transform
  • transform-origin
  • visibility
VisualElement

  • background-image
Page

  • border-color
Button, Frame, ImageButton

  • border-radius
BoxView, Button, Frame, ImageButton

  • border-width
Button, ImageButton

  • Color
ActivityIndicator, BoxView, Button, CheckBox, DatePicker, Editor, Entry, Label, Picker, ProgressBar, SearchBar, Switch, TimePicker

  • column-gap
  • row-gap
Grid

  • font-family
  • font-size
  • font-style
Button, DatePicker, Editor, Entry, Label, Picker, SearchBar, TimePicker, Span

  • letter-spacing
  • text-transform
Button, DatePicker, Editor, Entry, Label, Picker, SearchBar, SearchHandler, Span, TimePicker

  • line-height
  • text-decoration
Label, Span

  • margin
  • margin-left
  • margin-top
  • margin-right
  • margin-bottom
View

  • max-lines
  • vertical-align
Label

  • padding
  • padding-left
  • padding-top
  • padding-right
  • padding-bottom
Button, ImageButton, Layout, Page

  • text-align
Entry, EntryCell, Label, SearchBar

πŸ“ .NET MAUI Specific Properties

The following .NET MAUI specific CSS properties are also supported:

πŸ”§ PropertyπŸ“ Applies to

  • -maui-bar-background-color
  • -maui-bar-text-color
NavigationPage, TabbedPage

  • -maui-horizontal-scroll-bar-visibility
  • -maui-vertical-scroll-bar-visibility
ScrollView

  • -maui-max-length
  • -maui-placeholder
  • -maui-placeholder-color
Entry, Editor, SearchBar

  • -maui-max-length
  • -maui-placeholder
  • -maui-placeholder-color
Slider

  • -maui-orientation
ScrollView, StackLayout

  • -maui-spacing
StackLayout

  • -maui-thumb-color
Slider, Switch

  • -maui-vertical-text-alignment
Label

  • -maui-visual
VisualElement

πŸ“ .NET MAUI Shell Specific Properties

The following .NET MAUI Shell specific CSS properties are also supported:

πŸ”§ PropertyπŸ“ Applies to

  • -maui-flyout-background
Shell

  • -maui-shell-background
  • -maui-shell-disabled
  • -maui-shell-foreground
  • -maui-shell-tabbar-background
  • -maui-shell-tabbar-disabled
  • -maui-shell-tabbar-foreground
  • -maui-shell-tabbar-title
  • -maui-shell-tabbar-unselected
  • -maui-shell-title
  • -maui-shell-unselected
Element

🚫 Limitations

  • CSS variables are unsupported.
  • CSS sheets are parsed at runtime, not at compile time.
  • The following CSS selectors are unsupported:
         β—¦ [attribute]
         β—¦ @media and @supports
         β—¦ and ::
  • It’s not possible to style our applications 100% with CSS, so we can use XAML to complement.
  • It is not possible to change one style sheet at runtime for another.

Wrapping up

And done! 😎 In this article you have learned all the necessary information so that you can start adding styling to your .NET MAUI applications with CSS!

Thanks for reading this article! πŸ’šπŸ’•

See you next time! πŸ™‹‍♀️

References: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/styles/css?view=net-maui-7.0


Use a component library in sync with .NET MAUI’s release cadence. Try Telerik UI for .NET MAUI for free.

LeomarisReyes
About the Author

Leomaris Reyes

Leomaris Reyes is a Software Engineer from the Dominican Republic, with more than 5 years of experience. A Xamarin Certified Mobile Developer, she is also the founder of  Stemelle, an entity that works with software developers, training and mentoring with a main goal of including women in Tech. Leomaris really loves learning new things! πŸ’šπŸ’• You can follow her: Twitter, LinkedIn , AskXammy and Medium.

Related Posts

Comments

Comments are disabled in preview mode.