ASP.NET MVC: Use CSS on Html.ActionLink

I have seen plenty of mvc questions around applying CSS on an HTML.ActionLink, so I thought of writing a post to demonstrate how to do so.

We will use the default Site.master in a sample ASP.NET MVC application. The Menu link is declared similar to the following:

<div id="menucontainer">

ul id="menu">
li><%: Html.ActionLink("Home", "Index", "Home")%></li>
li><%: Html.ActionLink("About", "About", "Home")%></li>


Let’s apply a css class to the ‘About’ Link. To do so, declare a style in the Site.css file as shown below. The class is called 'custom'. Note: Site.css comes by default with the VS 2010 MVC template and is in the Content folder:


We will now apply this CSS to our Html.ActionLink. Use the following code:


We have used an overload of the ActionLink method where we are setting the routevalues to null and the htmlAttributes to the CSS class.






If you right click the page and view the source code, you will see that the 'About' link is decorated with class='custom".

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


b33ry said...

thanks for the helpful post. How do I add a tooltip to an ActionLink?

Suprotim Agarwal said...

b33ry: Use the 'title' attribute

<%=Html.ActionLink("About", "About", "Home", null,
new {title="This is a Tooltip" }) %>

Anonymous said...

Hey there
What if you needed to decorate the menu item of the current view?

Anonymous said...

to highlight the current view, try this post

himanshu pareek said...

How to hide link url from Browser's status bar .(Bottom on a browser, when mouse over on a link) ?