Using PHP to Switch CSS styles on a Web Page

CSS is a very powerful language to make the content of a web page look way you want it to look.  The new CSS3, when it's ready, promises to add another dimension to styling web pages and make it easier to do styling that now takes a little more effort with JavaScript.

One of the things that cause people problems, and is not built into CSS, is filtering CSS styles and applying one style if a certain condition exists.  In short, an "if" statement.

There are several workaround for this, one of which is to use PHP to switch styles depending on a condition.  Let's take a look at the way you normally include a stylesheet in a web page.

The CSS file, cssfile.css, might look something like this:

h1 {color: blue;}
p {color: purple;}

.reguser {color: purple;}

Now suppose we only want the text in class "reguser"  to show up, with its special purple color styling, if the user is registered on your site, and if the visitor is not registered, then the text will not be displayed.

Let's use PHP to set up the condition.

In the PHP portion we unset a variable that we will use to track a registered user to initialize the variable.  We then set the $user variable to true if a user registered on another web page, using a $_SESSION variable.

We then get to the "IF" statement.  "IF" the $user variable is NOT set, as in the visitor did not register on the site, we add another CSS include file.  As an aside, you could have just as easily added another CSS file with an "elseif" statement.

Most web pages have many CSS files included, so adding another CSS file is nothing unusual.  It is encouraged.  In fact, CSS defines rules called specificity and the Cascade, as in Cascading Style Sheets, that determine which styling rules apply if there is more than one style assigned to the same element.

Let's see what the second CSS file looks like to take out the registered user text on the web page.

.reguser {display: none;}

Well, that was easy.  The CSS says not to display the element, so it will disappear off the page, and the PHP lets you have conditionals in your web page styling.

Comments are closed.