cssmsbuildblazorvisual-studio-2022preprocessor-directive

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


Problem:

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:


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" />