Skip to main content

JSF 2.0: Adding Styles to the Spinner Component

Posted by driscoll on November 9, 2008 at 4:41 PM PST

In my last blog, I wrote a simple spinner component. In this posting, I'll add styling to it using the outputStylesheet tag, and a separate css file.


The tag is a way to output a cached stylesheet instance to a JSF page - just use it with a "name" attribute, where the name is the name of a css file in the resources directory of your web app. Since this is the same resources directory where you're already putting the composite component definition files, this means that you can now have a directory that looks like this:


  • resources/
    • spinnerStyled/
      • spinner.xhtml
      • spinner.css


We're also going to remind you how to override the existing styling of a component - so I'll also create a .css file for the calling page - we'll call it "calling.css", and place it in a higher level resource directory. So, here's the overall layout for our app now:


  • callingpage.xhtml
  • resources/
    • css/
      • calling.css

    • spinnerStyled/
      • spinner.xhtml
      • spinner.css


So, let's see what we've got - here's the part of the component file that we had to change to add styling, with the important parts marked in bold:



<composite:implementation>
    <h:outputStylesheet name="spinnerStyled/spinner.css" />
    <h:inputText id="number" value="#{cc.attrs.value}" styleClass="spinnerText"/>
    <h:panelGroup id="spinnerButtonPanel" styleClass="spinnerButtons">
        <h:commandButton id="forward"  value="&#652;"  onclick="return changeNumber(1);" styleClass="spinnerButton"/>
        <h:commandButton id="back" value="v" onclick="return changeNumber(-1);" styleClass="spinnerButton" />
    </h:panelGroup>


Note the stylesheet tag. Here's the stylesheet itself:



.spinnerText {
    text-align: right;
}

.spinnerButtons {
    width: 35px;
    display: inline-block;
    vertical-align: middle;
}

.spinnerButton {
    width: 30px;
    height: 20px;
}


Pretty straightforward: we wrap the buttons in a panel (i.e., a span), and change that to inline-block so that the buttons end up stacked on top of each other.


But now that we've got this set up with styling, we can do more with it as an enduser as well... Here's a fragment of the page that calls it:



<h:body><h1>Spinner Example</h1>
    <h:outputStylesheet name="css/calling.css"/>
        <h:form id="form1" prependId="false">
            <ez:spinner value="#{number.number}" increment="10" id="spinner" />
            <br/>


And, again, here's the styling of the calling.css page:



.spinnerText {
    width: 60px;
}


So, because we styled the component with individual classes, we can add additional styling without difficulty.


So, this covers using a separate css file for composite components, as well as the outputStylesheet tag. More in the next blog.

Related Topics >>