0

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

3
  • 1
    Just class wont override the properties by id. Commented May 26, 2016 at 14:51
  • @RejithRKrishnan Is there a different approach I could try? Commented May 26, 2016 at 14:54
  • I have added an answer. Commented May 26, 2016 at 14:55

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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.

Comments

-1

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

1 Comment

Better yet, reduce the specificity by using a different class for the base rules so the id isn't being used at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.