Search code examples
cssmsbuildblazorvisual-studio-2022preprocessor-directive

How can I use Preprocessor Directives to Conditionally Include Specific CSS Snippets?


Problem:

  • I have two build configurations. Each has its own preprocessor symbol: DEV and PROD.
  • I would like each build to have its own background-image color.
  • For C# files, I know that I can use preprocessor directives with the build symbols to conditionally generate code.

Question: How can I do this with a CSS file (like below)?

.page {
    position: relative;
    display: flex;
    flex-direction: column;
}

main {
    flex: 1;
}

.sidebar {
#if PROD
    background-image: linear-gradient(180deg, #ff80ed 0%, gainsboro 90%);
#else
    background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
#endif
}

UPDATE:

  • Alternatively, I'd be just as happy creating a site.css.dev and site.css.prod if that would solve the problem.

Solution

  • Inspired by this answer:

    1. Remove the .sidebar code from MainLayout.razor.css.
    2. Add two new files in the wwwroot\css directory:
      1. sidebar.Default.css

    .sidebar {
        background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
    }

    1. sidebar.Prod.css

    .sidebar {
        background-image: linear-gradient(180deg, #ff80ed 0%, gainsboro 90%);
    }

    1. Modify _Layout.cshtml as follows:

        <link href="css/site.css" rel="stylesheet" />
            @{
                var isProd = false;
                #if PROD
                isProd = true;
                #endif
            }
            @if (isProd)
            {
                <link href="css/sidebar.Prod.css" rel="stylesheet" />
            }
            else
            {
                <link href="css/sidebar.Default.css" rel="stylesheet" />
            }
            <link href="FooBar.styles.css" rel="stylesheet" />