9. Style the User Interface with CSS

We style the UI with the help of the HTML5 Boilerplate CSS and the browser style normalization file normalize.css. The two CSS files main.css and normalize.min.css are located in the WebContent/resources/css folder.

Adding the CSS to the HTML pages requires to edit the WebContent/WEB-INF/templates/page.xhtml file and add the style elements referencing the CSS files:

<h:head>
  <title>Public Library</title>
  <link rel="stylesheet" type="text/css" 
    href="#{facesContext.externalContext.requestContextPath}/
      resources/css/normalize.min.css" />
  <link rel="stylesheet" type="text/css" 
    href="#{facesContext.externalContext.requestContextPath}/
      resources/css/main.css" />
</h:head>

Notice that we also need to add the CSS to the WebContent/views/books/index.xhtml file, which is not generated with the page.xhtml template. The facesContext.externalContext.requestContextPath expression allows to get the path to WebContent folder. We then need to append the rest of the path, including the CSS file name, for each of the CSS files.

With JSF, there are two main ways to apply CSS styles to specific elements. For the elements created with JSF, we need to use the @styleClass attribute, e.g.:

<h:form id="createBookForm" styleClass="clearfix">
  ...
</hform>

For the HTML elements, we simply use the CSS classes, as in any normal HTML document, e.g.:

<div class="wrapper clearfix">
  ...
</div>

For creating advanced user interfaces, additional block elements that act as containers are used for defining paddings, margins, various background colors and other styles. Thus, in various HTML pages you may find DOM structures as shown below, where the div element containing the @class attribute is used as container for styling purposes:

<header>
  <div class="wrapper clearfix">
    <div class="title">
      <ui:insert name="headerTitle"/>
    </div>
    <ui:insert name="headerMenu">
      <ui:include src="/WEB-INF/templates/header.xhtml" />
    </ui:insert>
  </div>
</header>