Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change an element's CSS class with PHP

Tags:

css

php

How can I change a CSS class of an HTML element in response to a changing page using PHP?

I already got the solution exactly like in this but this solution is for Javascript.

Basically, I want to add additional class when a certain IF condition is met. This is my code.

<li <?php if ($selected == "profile") echo 'class="active"'; ?> class="dropdown">
<a href="">Profile</a>
</li>

From my code, you can see that the <li> already got a class in it. So, when I echo another class in IF condition, it completely change to the class in IF condition.

What I need is an extra class, not different class. How can I do that?

like image 773
user2781911 Avatar asked Nov 30 '22 18:11

user2781911


1 Answers

Just move it?

<li class="dropdown<?php if ($selected == "profile") echo ' active'; ?>">

This results in class="dropdown active", which is perfectly fine in HTML - you can have multiple space-separated classes on an element. All CSS rules targeting either of the two will be applied, and you can even combine them to require both:

li.active.dropdown {
  /* Underline active dropdown elements */
  text-decoration:underline;
}
like image 111
Niels Keurentjes Avatar answered Dec 04 '22 04:12

Niels Keurentjes