KnockoutJS - CSS Binding


This binding allows you to define CSS classes for the HTML DOM elements based on certain condition. This is useful in case you need to highlight some data depending on a situation.


css: <binding-object>


  • In case of static CSS binding, the parameter can be in the form of JavaScript Object, consisting of property and its value.

    • Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function.

    • Classes can be also applied dynamically using Computed Observable functions.

  • Multiple CSS classes can also be applied at once. Following is an example of how 2 classes are added to binding.

<div data-bind = "css: { 
   outOfStock : productStock() === 0, 
   discountAvailable: discount 
  • Class names can also be specified in single quotes such as 'discount Available'.

  • 0 and null are treated as false value. Numbers and other objects are treated as true value.

  • If the ViewModel property is an observable, then CSS classes are decided depending on the new updated parameter value. If it is not an observable value, then classes are determined only once for the first time.


Let us take a look at the following example which demonstrates the use of CSS binding.

<!DOCTYPE html>
      <title>KnockoutJS CSS binding</title>
      <script src = ""
         type = "text/javascript"></script>
         .outOfStock {
            color: red;
            font-weight: bold;
      <div data-bind = "css: { outOfStock : productStock() === 0 }">
         Product Details.

         function AppViewModel() {
            this.productStock = ko.observable(0);
         var vm = new AppViewModel();


Let's carry out the following steps to see how the above code works −

  • Save the above code in css-bind.htm file.

  • Open this HTML file in a browser.

  • Product Information is shown in a normal way when the productStockproperty is above 0. Product Information becomes red and bold. once productStock becomes 0.