In this tutorial we will learn how to use CSS binding in KnockoutJS or what is CSS binding in KnockoutJS or why use CSS binding in KnockoutJS with example.


knockoutJS CSS binding basically used to add or remove a css class from an element. CSS binding are particularly helpful when you want to change the style of an element depending on condition.

Let’s see a simple example of knockoutJS CSS binding.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnockoutJSCSSBinding.aspx.cs"
Inherits="AspDotNet.KnockoutJS_CSS_Bindings" %>
<!DOCTYPE html>
<html xmlns="">
<head runat="server">
    <script src="Scripts/jquery-3.1.1.min.js"></script>
    <script src="Scripts/knockout-3.4.2.js"></script>
      .eligible {
      color: red;
      font-weight: bold;
    <form id="form1" runat="server">
    Check Your Age :<input type="text" data-bind="value: Age" />
        <div data-bind="visible: Age() < 18">
              <div data-bind="css: { eligible: Age() < 18 }">
               your age is not eligible for vote.
       function VoteModel() {
           this.Age = ko.observable(0);
       var vm = new VoteModel();


How to use CSS binding in KnockoutJS

The above code. First go to the header section, here we have defined style. We have specify a class which changes the color of the text to bold and change its color. The name of the class is the “eligible”. Here inside the div we use data-bind attribute to set the css of the div to “eligible” if the use entered Age less than 18 in textbox. Notice the synax for css binding. It is similar to JavaScript object notation where the first parameter is the name object and second parameter is its value. The second parameter in this case is the expression. If this expression returns true, the “eligible” class will be applied to the div.

 I hope this article will help to you.

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like