Reputation: 231
In my html page, I use a PHP include to insert my site-wide header:
<?php include 'header.php'; ?>
Here is the code in header.php:
<div id="header">
<div id="navigation">
<ul>
<li><a href="index.php" class="active">home</a></li>
<li><a href="about_us.php" id="nav_about">about us</a></li>
<li><a href="competition.php" id="nav_competition">competition</a></li>
<li><a href="media.php" id="nav_media">media</a></li>
<li><a href="sponsors.php" id="nav_sponsors">sponsors</a></li>
<li><a href="contact_us.php" id="nav_contact">contact us</a></li>
</ul>
</div>
</div>
Here is the CSS in the header of the HTML document:
#nav_about { color:#4c005c; }
The "active" class in the inserted code is to change the color of that link to signify what page you are on. That functions fine, as "active" is defined in the CSS document linked to the html file. I want to modify the color of a particular link depending on what page it is included in. Thing is, the CSS on that page (the one defining #nav_about) does not apply when I test it out. The include works fine though.
In summary, I need to find a way to modify a site-wide snippet of HTML that is inserted via a PHP include with CSS on that page it is inserted in.
I am new to HTML and PHP, so I assume it is some lack of knowledge here.
Upvotes: 0
Views: 1646
Reputation: 71384
A simple way to do change the class of the HTML element based on the current page you are on in PHP might look something like this:
<?php
$nav_links = array(
'/index.php' => array('id' => 'nav_home', 'label' => 'Home'),
'/about_us.php' => array('id' => 'nav_about', 'label' => 'About Us'),
// and so on for each link
);
?>
<div id="header">
<div id="navigation">
<ul>
<?php
foreach ($nav_links as $href => $link_info) {
if ($_SERVER['REQUEST_URI'] === $href) {
?>
<li><a href="<?php echo $href; ?>" id="<?php echo $link_info['id']; ?>" class="active"><?php echo $link_info['label']; ?></a></li>
<?php
} else {
?>
<li><a href="<?php echo $href; ?>" id="<?php echo $link_info['id']; ?>"><?php echo $link_info['label']; ?></a></li>
<?php
}
}
?>
</ul>
</div>
</div>
Here you would just apply class=active
for the link that corresponds to the currently viewed page. This also makes it really easy to separate out you page/link configuration if you so desire.
Upvotes: 2
Reputation: 5239
Try using the traditional way, inside the PHP tags,
<?php
echo "<link rel='stylesheet' href='css-filename.css' type='text/css'>";
?>
Upvotes: 0
Reputation: 16325
Sounds like a selector specificity issue. What's the CSS for your navigation links?
If it's something like #navigation li {color: #abc}
, that will take priority over the #nav_about
selector.
Selector specificity is ranked by the number of ids, classes, and elements in each.
1 id + 1 element > 1 id.
Increase the specificity of the #nav_about
selector (e.g. change it to #navigation #nav_about
) and you should be fine.
Upvotes: 1