StyleBundle - Combine CSS Files in ASP.NET MVC
Here you will learn how to combine multiple CSS (Cascading Style Sheet) files to return it in a single HTTP request.
ASP.NET MVC API includes StyleBundle class that does CSS minification and bundling. Same as the script bundle, all the style bundles should be created in the BundleConfig
class.
under the App_Start
folder.
The following example shows how to combine multiple CSS files into a bundle.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/bundles/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"
));
// add ScriptBundle here..
}
}
In the above example, we created a new style bundle by creating an instance of the StyleBundle
class and specified the virtual path and bundle name in the constructor.
The ~/bundles/
is a virtual path and css
is a bundle name.
Then, we added two .css
files, bootstrap.css
, and site.css
in this bundle.
The bundles.Add()
method is used to add new bundles into the BundleCollection
.
By default, the above css
bundle will be created in the release mode. Use BundleTable.EnableOptimizations = true
if you want to see bundles in the debug mode.
Now, to include the above css
bundle in your webpage, use Styles.Render()
method in the layout view, as shown below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/bundles/css")
</head>
<body>
@*html code removed for clarity *@
</body>
</html>
Now, when you run the application in the release mode, you will see the bundle is created and loaded in a single request.
You can use the IncludeDirectory()
method, version wildcard {version}
, and CDN path the same way as ScriptBundle.
Learn how to set image path in StyleBundle.
BundleConfig.RegisterBundle()
from the Application_Start
event in the Global.asax.cs
file.
So, all the bundles are added into the BundleCollection
at the starting of an application.