Wednesday, January 19, 2011

How to use css in visual web part in sharepoint 2010

In this we will discuss how to use cascading style sheets (css) in visual web parts in SharePoint 2010.In my previous article I have explained in details:

- How to add custom web part properties to visual web part in SharePoint 2010?

- How to change date format in SharePoint 2010?

- Difference between Apps and Solutions in SharePoint 2013

To give style to a visual web part, a better approach is to use style sheet. To add a style sheet
First Right click on the project -> Add SharePoint Layouts mapped folder. Then visual studio 2010 automatically add the Layouts folder and all the contents will be deployed to the Layouts folder in the SharePoint root.

Within that folder sharepoint automatically create another folder with the name of the project. Within that folder you can add your css files.

How to call the css file?
To call the css file sharepoint provides CssRegistration control. Below is a sample code how to use that:

<sharepoint:cssregistration id="cssReg" name="/_layouts/ExpressionsWP/Style.css" runat="server"></sharepoint:cssregistration>

After that you can directly use the class name with the cssclass attribute. If you project name is Fewlines4WP the the css file will be deployed below:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\Fewlines4WP\Style.css