You have learned how to create a bundle of JavaScript files in the previous section. Here, you will learn how to create a bundle of style sheet files (CSS).

ASP.NET MVC API includes StyleBundle class that does CSS minification and bundling. StyleBundle is also derived from a Bundle class so it supports same methods as ScriptBundle.

As mentioned in the previous section, you should create bundles of script and css files in the RegisterBundles() method of BundleConfig class contained in App_Start -> BundleConfig.cs file.

The following code shows a portion of the RegisterBundles() method.

Use ScriptsInclude or IncludeDerictory method to add css files into bundle as shown below:

Example: StyleBundle

public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new StyleBundle("~/bundles/css").Include(
        // add ScriptBundle here..  

As you can see in the above example, we have created StyleBundle instance with bundle name as virtual path. The bundle name (virtual path) must start with ~/. Use Include() or IncludeDirectory() method with css file names as a string.

You can use wildcard and CDN path the same way as ScriptBundle as shown in the previous section.

Include Style Bundle in Razor View:

You can use StyleBundle in a layout view and render bunch of css files in a single request using static Styles class. Styles is a helper class to render css bundles.

Example: Include Style Bundle in View

<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @*html code removed for clarity *@

As shown in the above example, use Styles.Render() method to include specified css bundle at runtime. Open developer tool of the browser and check that it has minified and loaded css files as shown below.

Load Bundle in Browser
Load Bundle in Browser

Further Reading:

Points to Remember :

  1. Bundling and Minification minimize static script or css files loading time therby minimize page loading time.
  2. MVC framework provides ScriptBundle, StyleBundle and DynamicFolderBundle classes.
  3. StyleBundle does minification of CSS files.
  4. Create script or css bundles in the BundleConfig class included in App_Start folder.
  5. Use wildcard {version} to render available version files at runtime.
  6. Use Styles.Render("bundle name") method to include style bundles in a razor view.