Dan
Dan

Reputation: 7724

JavaScript and CSS classes not acting as expected

I have set up a custom navigation bar which when I am scrolling through a website slides the current nav which is occupying the majority of the screen out slightly.

Example extracts from the CSS and JS are as follows

/*CSS*/
#topnav {
    top: 100px;
    background-color:white;
    border-top-style:solid;
}

.topActive {
    z-index:5000;
    width:3cm;
    background-color:black;
    border-style:solid;
    border-right-style:none;
    color:white;
}

/*JS*/
if(nav == 0) {
    $("#topnav").addClass("topActive topnavb");
    ...

In this example, I would expect that when the nav tab in the nav bar slides out the background colour of it is black; however, in this case, the background colour would be white still. Essentially the class is not overriding the properties in the id

I would appreciate any help in fixing this problem

Upvotes: 0

Views: 69

Answers (4)

Dan
Dan

Reputation: 7724

After reading up on specificity which the other answers have been talking about I found a command which can be added to the end of the line. This is !important. Even though !important is normally considered bad practice, see here for more about the practice of using !important, in this case it is not considered bad practice. This is because it is overriding one property which is otherwise unchanged in any further use of style sheets in this website.

Upvotes: 0

Francisco Romero
Francisco Romero

Reputation: 13189

It is because of the CSS specificity. From the link:

The following list of selector types is by increasing specificity:

  • Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
  • Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
  • ID selectors (e.g., #example).

So an ID will always override a class.

Upvotes: 2

wilovent
wilovent

Reputation: 1364

Browsers will choose the property that is defined in the more precise rule. Id selectors are more precise than class selectors. You juste have to use #topnav.topActive instead of .topActive

Upvotes: -1

Eric N
Eric N

Reputation: 2206

The css specificity of a class is lower than that of an id. This causes id rules to override class rules.

https://css-tricks.com/specifics-on-css-specificity/

Upvotes: 0

Related Questions