Sunday, 3 August 2025

Use CSS in MAUI

 1. Add a CSS File

  • Create a .css file in your project (e.g., Styles/styles.css).

  • Set the Build Action to MauiCss (right-click the file > Properties > Build Action).

2. Apply CSS to Controls

  • Option 1: Apply globally via App.xaml

    xml
    <Application.Resources>
        <StyleSheet Source="Styles/styles.css" />
    </Application.Resources>
  • Option 2: Apply to a specific page

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

3. Supported CSS Selectors & Properties

MAUI CSS supports a limited subset of CSS, including:

Selectors

  • By Type (ButtonLabel, etc.)

    css
    Button {
        background-color: #3498db;
        color: white;
    }
  • By Class (.my-class)

    css
    .my-label {
        font-size: 18;
        font-weight: bold;
    }

    Apply in XAML:

    xml
    <Label Text="Hello MAUI!" StyleClass="my-label" />
  • By ID (#myButton)

    css
    #myButton {
        background-color: red;
    }

    Apply in XAML:

    xml
    <Button x:Name="myButton" Text="Click Me" />

Supported Properties

CategoryExample Properties
Textcolorfont-sizefont-weightfont-style
Backgroundbackground-color
Borderborder-colorborder-width
Layoutmarginpadding
Visibilityvisibility (true/false)

Example: Styling a Button

styles.css

css
Button {
    background-color: #3498db;
    color: white;
    font-size: 16;
    margin: 10;
    padding: 12;
}

Button:pressed {
    background-color: #2980b9;
}

.my-special-button {
    background-color: #e74c3c;
    border-radius: 20;
}

MainPage.xaml

xml
<Button Text="Click Me" />  <!-- Uses default Button style -->
<Button Text="Special Button" StyleClass="my-special-button" />

Limitations of CSS in MAUI

  • ❌ No full CSS support (only a subset of properties).

  • ❌ No animations, transitions, or pseudo-classes (except :pressed).

  • ❌ No Flexbox/Grid layouts (use MAUI's Grid/FlexLayout instead).

  • ❌ No media queries (use OnPlatform in XAML instead).

No comments:

Post a Comment

Complete Guide: Building a Live Cricket Streaming App for 100M Users

Comprehensive guide to building a scalable live cricket streaming platform for 100M users, covering backend infrastructure, streaming techno...