androbin
androbin

Reputation: 1759

CSS id under class

I want to make the easiest css for menus. There's an outer div and an inner anchor. If the outer's class is the same as the inner's id, that will be active styled. Example code:

<div class='<?php echo $_GET['menu']; ?>'>
     <a href="index.php?menu=menu1" id='menu1'>Menu 1</a>
     <a href="index.php?menu=menu2" id='menu2'>Menu 2</a>
     <a href="index.php?menu=menu3" id='menu3'>Menu 3</a>
     <a href="index.php?menu=menu4" id='menu4'>Menu 4</a>
     <a href="index.php?menu=menu5" id='menu5'>Menu 5</a>
</div>

and I don't want to write a lot of css, like:

.menu1 #menu1, .menu2 #menu2, .menu3 ....
{ /*active stlye*/}

so I want the following: if the classname is the same of the id under it would be active.

Thanks in advance.

Upvotes: 0

Views: 710

Answers (3)

Zeta
Zeta

Reputation: 105876

That's not possible. CSS isn't a programming language, you have to fully specify every selector.

But since you already work with PHP it would be a lot easier if you apply the class to one of your anchor tags:

<div class='<?php echo $_GET['menu']; ?>'>
     <a href="index.php?menu=menu1" <?php echo $a_class[1]; ?> id='menu1'>Menu 1</a>
     <a href="index.php?menu=menu2" <?php echo $a_class[2]; ?> id='menu2'>Menu 2</a>
     <a href="index.php?menu=menu3" <?php echo $a_class[3]; ?> id='menu3'>Menu 3</a>
     <a href="index.php?menu=menu4" <?php echo $a_class[4]; ?> id='menu4'>Menu 4</a>
     <a href="index.php?menu=menu5" <?php echo $a_class[5]; ?> id='menu5'>Menu 5</a>
</div>

You have to either specify a bunch of selectors or add code to your PHP script.

Upvotes: 0

darma
darma

Reputation: 4747

You can't do that with CSS ; maybe you could instead use PHP to accomplish something close :

<?php for($i=1;$i<=5;$i++){ ?>
<a href="index.php?menu=menu<?php echo $i;?>" <?php if($_GET['menu'] == 'menu'.$i) echo 'class="selected"'; ?>>Menu <?php echo $i;?></a>
<?php } ?>

And the CSS :

        .selected{
/*active style*/
        }

Edit : a solution with PHP is better than one based on JS because : everyone will see the .selected class, even people who have JS deactivated + for the others, the menu will not blink. Honestly it is super annoying to see a menu CSS changed via JS.

Upvotes: 1

Jerska
Jerska

Reputation: 12002

Let's suppose I got you well. Then an answer could be :

<div id="menu">
<?php
    for($i = 0; $i < 5; $i++) {
        if(isset($_GET['menu']) && $i == $_GET['menu'])
            echo "  <a href=\"index.php?menu=$i\" id=\"menu$i\" class=\"menu_active\">Menu $i</a>";
        else
            echo "  <a href=\"index.php?menu=$i\" id=\"menu$i\">Menu $i</a>";
    }
?>
</div>

And in your CSS

#menu a {
    /* Whatever you want for your normal links */
}

#menu .menu_active {
    /* Whatever you want for your active link */
}

And that's it !

Upvotes: 0

Related Questions