Font Awesome in ASP.NET MVC WebGrid
When redesigning Bonobo Git Server I’m using an amazing icon library Font Awesome. The usage is really simple and when you want to add an icon to your paragraph you just insert <i>
tag with specific CSS classes.
<p><i class="fa fa-camera-retro"></i> fa-camera-retro</p>
However, there are some HTML components where it is hard to add any custom HTML and one of them is WebGrid. Imagine you have a code similar to this one.
var grid = new WebGrid(source: Model, defaultSort: "Name");
@grid.GetHtml(
tableStyle: "myGrid",
columns: grid.Columns(
...
grid.Column("Name",format: item => Html.ActionLink(...),
...
))
And you want add an icon from Font Awesome library to the Name column. You can’t simply modify HTML inside the column, so one of the options would be writing your custom HTML helper. But I don’t find this situation to be general enough to earn its own helper. So, is there any other way around?
You might think that Font Awesome is a set of icons, but actually it is a font face. And with font face you can do some CSS magic.
.myGrid tbody td a:before {
font-family: FontAwesome;
top: 0;
padding-right: 0.5em;
content: "\f0a0";
}
With that code, we add a content before every link inside the body of our grid. The content is a code for an icon you want to show and you can find it here; mine is for a small icon of a hard-drive and that’s it. Awesome!