Reputation:
I know the title is kinda vague, sorry. I could'nt express it easily in one statement. So, anyways.
I'm currently working on my Personal Website. I wanted to have the nav element for the current page to be highlighted a certain color. To do so I wanted to use this:
<a href="index.php" class="nav-item" <?php if($current =='home'){echo 'class = "active"';}?>>Home</a>
and the same thing for the other pages. However, "class = "active" is not even being applied to the a tag. My Index pages contains this:
$current = "home";
and the css for the active class looks like this:
.active{
background-color: #fdfdfd !important;
color: #3D1c4B;
}
I seriously don't know what I'm doing wrong. Is there something I'm missing or is this just something I can't do with an a element?
Here is what the nav looks like
Upvotes: 0
Views: 57
Reputation: 6755
your code will add 2 classes so that only one class will be applied to your tag.
try like this.
<a href="index.php" class="nav-item <?php if($current =='home'){echo 'active';}?>">Home</a>
Upvotes: 0
Reputation: 416
First, I see your using:
<a href="index.php" class="nav-item" <?php if ( $current =='home' ) echo 'class = "active"'; ?> >Home</a>
is wrong, since you will get class="nav-item" class="active"
, - instead you need to write:
<a class="nav-item <?php if ( $current =='home') echo 'active'; ?>" href="index.php">Home</a>
Upvotes: 0
Reputation: 8249
Get the class in a variable and use it like this:
<?php
$className = '';
if($current =='home'){
$className = 'active';
echo "<a href='index.php' class='nav-item " . $className . "'>Home</a>";
?>
Upvotes: 0
Reputation: 805
You are writing class
attribute two times in <a>
tag
<a href="index.php" class="nav-item" <?php if($current =='home'){echo 'class = "active"';}?>>Home</a>
it should be like
<a href="index.php" class="nav-item <?php if($current =='home'){echo
' active'; }?>" >Home</a>
Upvotes: 0
Reputation: 26160
Your HTML is invalid, and would render: <a href="index.php" class="nav-item" class="active">
- which has two class
attributes (not legal). Modify your PHP like below, to put both classes in the same attribute:
<a href="index.php" class="nav-item<?php if($current =='home'){echo ' active';}?>">Home</a>
Upvotes: 0
Reputation: 10447
You can't have multiple class tags, you already have one you can't add a second. Try this:
<a href="index.php" class="nav-item<?= $current == 'home' ? ' active' : '' ?>">Home</a>
Upvotes: 3