CSS In Xamarin.Forms

Xamarin.Forms now supports CSS styling, in addition to the existing Styles, from version 2.6.0. This allows you to use CSS as you would on the web, in a Xamarin.Forms application.

Note: As of the time I am writing this, I am using code from the master branch, it hasn’t even hit the nightly build yet. Considering the nightly build is at 2.6.0, I am speculating this feature will be released in the 2.6.0 release. I will update if this changes.

Create Stylesheet

  1. Create a style.css empty file in your class library project, and set the build action to an EmbeddedResource.
  2. In your ContentPage, add the stylesheet.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App"
             x:Class="App.MainPage">
    <ContentPage.Resources>
        <StyleSheet Source="style.css" />
    </ContentPage.Resources>

In your style.css, is just a regular css file. e.g.

stacklayout {
    margin:10;
}

Selectors

CSS uses selectors to determine which elements to target. Most are the same as regular CSS, an exception. These selectors certainly allow more flexibility in styling.

SelectorExampleDescription
.class.classNameSet the StyleClass property on the element. e.g. className
#id#emailEntryChecks StyleId, or fallbacks to x:Name
**For all elements
elemententrySelects all elements of type entry, but not subclasses.
^base^contentpageAny element with this as a base class, including itself. This is the XF specific selector.
element,elementlabel, entrySelecting multiple elements
element elementcontentview labelAny labels inside a ContentView
element>elementcontentview>labelSelects labels, that are a direct child of a ContentView
element+elementlabel+entryAll entry elements that come directly after a label
element~elementlabel~entryAll entries that have a label before it.

Other selectors you may be used to in CSS aren’t available yet. You can also combine selectors if you want. A small note that !important is not supported, hence ensuring the correct ordering of styles is essential. Styles get applied in order, hence the last one defined, wins.

Property Support

This was taken from PR 1207 for readability.

PropertyApplies toExamples
background-colorVisualElementbackground-color:blue;
background-imagePagebackground-image:image.png
border-colorButton, Frameborder-color:#7aff67; (see colors)
border-widthButtonborder-width:1;
colorButton, DatePicker, Editor, Entry, Label, Picker, SearchBar, TimePickercolor:#447799; (see colors)
directionVisualElementdirection:rtl;
font-familyButton, DatePicker, Editor, Entry, Label, Picker, SearchBar, TimePicker, Spanfont-family:'Open Sans';
font-sizeButton, DatePicker, Editor, Entry, Label, Picker, SearchBar, TimePicker, Spanfont-size:12;
font-styleButton, DatePicker, Editor, Entry, Label, Picker, SearchBar, TimePicker, Spanfont-style:bold;
heightVisualElementheight:100;
margin
margin-left
margin-right
margin-top
margin-bottom
Viewmargin:3; (see thickness section below)
min-heightVisualElementmin-height:100;
min-widthVisualElementmin-width:100;
opacityVisualElementopacity:0.5;
padding
padding-left
padding-right
padding-top
padding-bottom
Layout, Pagepadding:0; (see thickness section below)
text-alignEntry, EntryCell, Label, SearchBartext-align:right;
visibilityVisualElementvisibility:hidden;
widthVisualElementmin-width:100;

Thickness

This is similar to XF:

  1. A single value, that is a uniform thickness (e.g. 2)
  2. 2 values, indicating vertical, horizontal (e.g. 2, 4)
  3. 3 values, indicating top, horizontal (left and right), bottom thickness (e.g. 3, 4, 5)
  4. 4 comma delimited values. However, the 4 values are in a different sequence. top, right, bottom, left. (e.g. 2, 3, 4, 2)  – TRBL instead of LTRB

Colors

Colors are similar to what you are used to. You can use:

  1. Hex (#78f6a7)
  2. X11 names
  3. RGB
  4. RGBA
  5. HSL
  6. HSLA

CDATA

If you want to have your CSS on your page, without creating a new file, you can use CDATA.

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

Load Style In Code Behind

APIs have been exposed to let you load a stylesheet from code behind, however, I recommend you use XAML.

From an EmbeddedResource

this.Resources.Add(StyleSheet.FromAssemblyResource(this.GetType().Assembly, "css.id"));

From a TextReader

using (var reader = new StringReader("^contentpage { background-color:blue; }"))
    this.Resources.Add(StyleSheet.FromReader(reader));

Learn More

As of writing this, there is no documentation, however PR 1207, is the main pull request for this feature, and it details more information in its notes. I used this as the source for this post, along with a bit of playing around myself. It’s certainly fun and interesting to play around with, I never expected CSS to be available in Xamarin.Forms.

On a personal note, I was against this addition, and I still mostly am, and would have much preferred Xamarin invested the effort into enhancing the current styling system.

However, CSS does have its benefits, particularly with theming, selector flexibility, and reduced verbosity over XAML. Theming is probably the most promising potential of this Xamarin.Forms addition, only the future will tell if the community picks it up and runs with it. It will also likely help developers coming from a web background to mobile, but If you are on a project in the future, I would recommend picking Styles or CSS and not mixing the two.

In regards to visual previewers, it is likely that they should also be able to support this change, as is, with no changes on their end, but it all depends on how they implemented their previewer, and there are likely to be teething issues.


XAMARIN WEEKLY NEWSLETTER

Subscribe to a hand-picked round up of the best Xamarin development links every week. Published every Friday. Free.

Signup to Weekly Xamarin

* I do not maintain or run this newsletter, but I do recommend it.

Microsoft MVP | Xamarin MVP | Xamarin Forms Developer | Build Flutter

Related Posts

7 Comments

  1. Mikem

    I’m sorry but such a feature is so weird for a XAML platform, especially Xamarin Forms and especially since Xamarin is Microsoft.
    It looks like Xamarin Forms management continues on same path, adding bells and whistles without really nailing the core and more important stuff. The usual answer is “but we do that, look to the bug fixing and performance” but in reality after years XF is still like a sieve, there are still bugs in the basic stuff or just missing, or partly implemented. Im talking about stuff related to basic controls, data binding, etc. Even the live player doesn’t work with dependencies. And development team remains to be small.

  2. Mikem

    I will not use nor recommend to anyone this “styling” feature. I don’t event want to think about implications it has in terms of speed and bugs. In a team, in a serious project. Things can go crazy fast.

  3. Jesse Liberty

    I think the previous comments are overly sceptical… if Xamarin gets it right, this could be a killer feature for styling serious apps. Clearly we’d all like a real designer for Xamarin.Forms but while they may be quietly working on that, it isn’t here and won’t be for a while.

    Adam, please do keep us up to date on when and how this is available.

  4. Mikem

    Skeptical? I am not in any business where I feel like I need to promote Xamarin just so I feel like in the pack, no matter what.
    I’m speaking as someone who develops with Xamarin every day and I’m also a long time XAML developer.
    The way Xamarin Forms has been managed and the decisions to invest time in such features like CSS styling and Flexbox and God knows what else, when you both have a small team and there are bugs sitting there some of them since a year or two ago, and they are related to the most basic things like controls, how do you call that? You think I am skeptical? I think it’s Xamarin Forms is still unfortunately a mediocre product. And it’s mostly because of they it has been managed and decisions which were made.

  5. Mikem

    This isn’t looking as a XAML framework anymore. It’s starting to look like a bunch of people throwing some ideas and code of could look cool to have, like it’s a fun gig.

  6. Johnny Goobox

    More pointless variation that xaml standard will have to deal with. Please deprecate this stuff immediately.