简体   繁体   中英

Why can't I apply other css elements to my custom css class?

I have a css class which is supposed to darken the background of an element in my header menu. I've tried applying many different things to it, like:

.menu-highlight; a:hover; .active; .current_page_item; .current-menu-item a; .current-menu-parent a; .current-menu-ancestor; .current_page_parent a; .current_page_item .sub-menu a; :active, :focus.

None of them are working and I also don't see it in the the CSS rules when searching with the inspector tool. It's most likely overridden by another rule, but I can't seem to find out which one. This is the css class:

ul.test li.active a{
    background-color: #808080;
    color: #fcfcfc;
    float: left;
}

Here is a link to where it gets applied through a JS script, not a class: https://jsfiddle.net/mguxsj10/ . This is what I want to achieve with this. But instead of using JavaScript I wanted to use CSS.

Edit : To give you an example of the problem showing up take away the JS code from the jsfiddle from above and then test the menu. This is what it's like: https://jsfiddle.net/wkurv56x/ and exactly this is my problem. No matter what I'm adding to this CSS class, it always stays like in the example of the jsfiddle without JS code.

if you're not able to find it try adding !important but it's not recommended as it cannot be overridden. like

ul.test li.active a{
    background-color: #808080 !important;
    color: #fcfcfc !important;
    float: left !important;
}

or simply add an id to your element and add css rules, as id has the highest specificity.

The solution is to add !important after each custom style you need to overwrite. I believe this is what you need to achieve the expected behavior:

 ul.test li.active a{
        background-color: #808080 !important;
        color: #fcfcfc !important;
        float: left !important;
    }

Here is a fiddle link with alternate styles implemented https://jsfiddle.net/w3br10ve/

As I could Understand you want to have a dark background on a clicked item. Well you must use JS to provide this, so you must trigger click listener and add active class to that item. You are trying to add dark background to item with active class but you're not adding active class on click.

your code will not work without JS code because you are adding and removing your active class through it. When you click on an li it add the active class into it and remove active class from everything else. And you write your styling into your css code. If you need to change the background depend on click you must add js to add and remove it dynamically.

$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')

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