Override CSS styles in Asp.net MVC3 razor


  • CSS - Cascading Style sheets plays an important part in designing our HMTL pages and making them look good.
  • Often we land up in scenario where we want to override the CSS property already applied to controls.
  • We use third party controls like Telerik. Often we come across scenario where we want to override the CSS applied to telerik controls by default.
  • In this article, we will see how to override the existing CSS property and apply the CSS styles we want.
Example 1 :

<html>
    <head>
        <title>OverRidding CSS</title>
        <style type="text/css">
            div {
                color:Green;
                font-size:30px;
            }
        </style>
    </head>
    <body>
        <div style="color:Red;">Hello world</div>
    </body>
</html>

Demo :




In the above example, we have created a div. We have applied CSS to div using element selector and by using inline style as well. You must have noticed, the font-size property is applied from element selector, but color property is applied from inline style. This is the default rule. The inline CSS overrides the property defined at class or page level.


Example 2 : overriding inline style property


!important - By appending !important after the property we can prevent the inline CSS overriding the page level or class level CSS property. 



<html>
    <head>
        <title>OverRidding CSS</title>
        <style type="text/css">
            div {
                color:Green!important;
                font-size:30px;
            }
        </style>
    </head>
    <body>
        <div style="color:Red">Hello world</div>
    </body>
</html>

Demo :




In the above example, we have used !important after the color property. Therefor the inline color property fails to override the color property defined with !important using element selector. In this example, color of text is Green.


Example 3 : Overriding class level property


In some scenarios, we want to apply style defined at inline or control level, but some class level property prevents it from overriding as !important is used at the class level. In this scenario we can apply inline style as shown below.




<html>
    <head>
        <title>OverRidding CSS</title>
        <style type="text/css">
            div {
                color:Green!important;
                font-size:30px;
            }
        </style>
    </head>
    <body>
        <div style="color:Red!important;">Hello world</div>
    </body>
</html>

Demo :




In the above example, we have used !important at inline style. So even though the style property is defined with !important at class level, inline style will override it. 


Thus we can override any style property bu using !important after the property value before semi colon. This helps greatly in overriding CSS of Third party controls like Telerik.

0 comments:

Post a Comment