How to show the "active" instead of "first child"?

时间:2016-12-02 04:46:40

标签: html css

I'm still trying to learn css and html here :P Anyway I got this code from this site http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav maybe you guys are familiar

...
    @media screen and (max-width:680px) {
      ul.topnav li:not(:first-child) {display: none;}
      ul.topnav li.icon {
        float: right;
        display: inline-block;
      }
    }
...

I wanted to show the one that is active instead of the first-child

2 个答案:

答案 0 :(得分:2)

That would be done by adding class active inside :not ,

@media screen and (max-width:680px) {
      ul.topnav li:not(.active) {display: none;}
      ul.topnav li.icon {
        float: right;
        display: inline-block;
      }
}

But the active class is not getting added to the selected item in the given example I guess.

Update Please see this fiddle : https://jsfiddle.net/arshadmuhammed/Lpuv6pwc/4/ to see how it is done. And please note that I have made some changes in CSS and included jQuery and added some javascript too.

CSS Modification

li.active {
  background: red;
}

HTML Modification Instead of giving active class to a tag I have given it to the li itself,

<li class="active"><a href="#news">News</a></li>

Added javascript/jQuery code

$('#myTopnav li').click(function() {
  $('#myTopnav li').removeClass('active');
  $(this).addClass('active');
});

This will make the selected menu active.

答案 1 :(得分:1)

只需更改:first-child

:active即可

修改 对不起,我没有正确理解你。我正在努力演示如何做到这一点。