简体   繁体   中英

How To Set CSS Classes On HTML Tags Which Are Included In The Page With PHP Include's

I'm building a website which uses a lot of repeated styles and HTML tags, such as the header, the navigation bar at the top, and the footer at the very bottom. Instead of typing all of that repeated code in again and again, I'd like to use PHP include statements to include everything that I need.

While that's all well and good, this poses a problem with my navigation bar. I use a CSS class attached to the navigation link to let the user know what page they're on (using a different background color). On each page, I manually specify which link gets that special class. If I were to simply include that content via a PHP include statement, I couldn't manually specify the class.

My question is: how would I be able to do that? Either by using a separate PHP script to find out which page the user is on, and then specify the class to style the link appropriately, or by using JavaScript to do the same thing? Or maybe there's something else that I'm missing? Who knows! And as such, I ask!

An easy way to do it would be to add a PHP variable like $page before the include and then use this variable in your included menu file to determine which menu item needs highlighting.

So in the file with the includes:

$page = "home";
include("menu.php");

And in the menu file:

<ul>
    <li <?php if( $page == "home") echo 'class="active"' ?> >home</li>
    <li <?php if( $page == "about") echo 'class="active"' ?> >about</li>
    <li <?php if( $page == "contact") echo 'class="active"' ?> >contact</li>
</ul>

The example above isn't the tidiest or most optimal solution, but it gives you an idea of how you could achieve what you are trying to do by using PHP variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM