CSS parser for .NET written in C #

    It took me one day to parse CSS, to remove @import, url(). But for .NET there were only varying degrees of crooked crafts. ExCSS was the best library, but it bent on trivial things like media queries. So I decided to fill in the gap.

    There were options: picking up Chrome, picking up Firefox, picking up the left library. We needed guaranteed quality and regular updates, so the last option was no longer needed. In Chrome, CSS and HTML parsing was generated based on grammars, and a cursory study of the variety of tools for .NET was disheartening, let alone tool compatibility, so Chrome was no longer there. Remained Firefox with manually written parsers.


    How long, briefly, the result is a library that fully parses the CSS files fed to it. Tests in Firefox turned out to be too problematic to convert, and they are not unit tests at all: they are written in JS, they are inside HTML. Therefore, to fully verify the operation of the library was problematic. If anyone has any suggestions on where to get good unit tests for CSS - I pay all the attention. I really hope that the library will be useful to at least someone, and if there are problems, I will be informed about this.

    What is available

    • All rules, properties, values, etc. supported by Mozilla Firefox are supported. FF-specific extensions ( -moz-*) including.
    • Two compatibility modes: Full Standards (strict adherence to standards) and Quirks (you can not specify units of measurement and allow other similar liberties).
    • All values ​​are parsed into complex structures. The short property backgroundwill expand into several properties, including background-imageone that contains a list of background images, each of which is a URL or gradient; in the latter case, the gradient will contain individual points and all parameters.
    • Error handling in accordance with all specifications. If something does not recognize, then the parser will simply skip an incomprehensible piece.
    • Detailed error logging. All warnings about incorrect syntax and properties are dumped in TraceSource "Alba.CsCss.CssParser"and throw an event.

    What is not available

    • Support for encodings. In unicode, you need to throw it yourself.
    • Modification and conversion back to string.
    • DOM CSS. The interface from the point of view of C # coding standards is very doubtful, so the benefit is in question.
    • Properties with vendor prefixes of other browsers (-webkit-, -ms-, -o-) are ignored.
    • .NET 4.0 and below. From .NET 4.5 is used perhaps IReadOnlyList, but so far messing with versions is a bit lazy.
    • NuGet package. Damp while the library.

    I plan to add encodings, modification, serialization, .NET 4.0 and the NuGet package. How soon this happens will depend on whether anyone needs it.

    Usage example

    // Распарсить CSS, указав URL файла (для логирования) и базовый URL (для резолва относительных урлов)
    CssStyleSheet css = new CssLoader().ParseSheet("h1, h2 { color: #123; }",
        "http://example.com/sheet.css", "http://example.com/");
    Console.WriteLine(css.SheetUri); // http://example.com/sheet.css
    // Получить цвет (варианты равносильны)
    Console.WriteLine(css.StyleRules.Single().Declaration.Color.Color.R); // 17
                                   .Data.Single().Color.R); // 17
                                   .GetValue(CssProperty.Color).Color.R); // 17
    // Получить тег в первом селекторе
    Console.WriteLine(css.StyleRules.Single().SelectorGroups.First().Selectors.Single().Tag); // h1

    Project assembly

    • Alba.CsCss- the library itself. Has no dependencies on other projects. If you want to use the library in your solution, just turn on this project.
    • Alba.CsCss.Tests- unit tests. The amount is such that in a decent society it is customary to remain silent.
    • Alba.Framework- A personal collection of bicycle frameworks. Simplifies code in T4 transformations. To run these, you need to build a Debug version.
    • Alba.Framework.CodeGeneration- T4 part of the framework. It must be collected under the admin account to install the custom tool “AttachT4” (related to the T4 Toolbox, only without a ton of unnecessary features). It is necessary if you want to work conveniently with T4 in a project.
    • Alba.Framework.Testing - used in tests.


    Mozilla Public License . A mixture of BSD with the GPL. Virus-like GPL, but infects only individual sorts files with MPL code. Everything else does not bother the license. There are no restrictions on the use with projects under other licenses, including commercial ones with closed source code.

    Of course, I would prefer to release the library under a more liberal and understandable BSD / MIT license, but the MPL “infected” most of the files, so there were no options.


    The library is written. Whether it will evolve depends on whether it will be used. I myself only need a small part. I hope for bug reports, and possibly even pull requests, if there are any bold ones.

    If you need a CSS parser, then please write how you are going to use it. It is very important to understand the further development path and priorities.


    PS How did I convert the library, what were my goals, etc. - stripped down in ReadMe on GitHub. Habr did not appreciate my attempt to tell about ordeals, therefore only dry facts. Good to all.

    Also popular now: