In this recipe, you will see how to add CSS styles to JSF tags. It is a simple solution, but it has the advantage that it can be applied to almost all JSF tags that render text, images, and so on.
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
When you need a simple and classic solution to integrate CSS in JSF it is important to know that JSF components support the styleClass
and style
attributes. The styleClass
attribute is used when you are working with CSS classes, while the style
attribute allows you to place CSS code directly in place between quotes.
You can see in the following code snippet how this works with the h:outputText
component:
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>JSF and CSS example</title> <style type="text/css"> .message { text-align: left; letter-spacing:5px; color:#000099 } .message-overline { text-decoration:overline; } .message-font { font-family:georgia,garamond,serif; font-size:20px; font-style:italic; } </style> </h:head> <h:body> <h:outputText styleClass="message" value="This text is CSS formated by 'message' class!"/> <br /><br /> <h:outputText styleClass="message message-overline" value="This text is CSS formated by 'message' and 'message-overline' classes!"/> <br /><br /> <h:outputText styleClass="message message-overline message-font" value="This text is CSS formated by 'message', 'message-overline' and 'message-font' classes!"/> <br /><br /> <h:outputText style="text-align: left;letter-spacing:5px; color:#000099" value="This text is CSS formated using the 'style' attribute instead of 'message' class!"/> <br /><br /> <h:outputText style="text-align: left;letter-spacing:5px; color:#000099;text-decoration:overline;" value="This text is CSS formated using the 'style' attribute instead of 'message' and 'message-overline' classes!"/> <br /><br /> <h:outputText style="text-align: left;letter-spacing:5px; color:#000099;text-decoration:overline; font-family:georgia,garamond,serif; font-size:20px;font-style:italic; " value="This text is CSS formated using the 'style' attribute instead of 'message', 'message-overline' and 'message-font' classes!"/> <br /><br /> </h:body> </html>
Notice that when you need to specify more CSS classes under the same styleClass
you need to separate their names by space.