skip to Main Content

I am trying to create a hover:before and a hover:after for my menu navbar. The menu contain 7 items:

menu 1, menu 2, menu 3 (these will use hover:before)

logo in the middle (in place of menu 4)

menu 5, menu 6, menu 7 (these will use hover:after)

I can select the menu from 1 to 3 like this:

menu:hover:nth-of-type(-n+3)::before {background:red}

But how do I select from 5 to 7 ?

I am trying like this:

menu:hover:nth-of-type(5+-n)::after {background:green}

Also tried (5,6,7), (5-7) but I cannot understand how this is done.
I tried looking for answers from previous questions here but cannot find an answer for this specific case.

Any idea?

EDIT:
Here is the HTML

<nav role="navigation">
<menu><a href="#">1</a></menu>
<menu><a href="#">2</a></menu>
<menu><a href="#">3</a></menu>
<menu>
<logo><img src="logo.png"></logo>
<slogan>slogan here</slogan>
</menu>
<menu><a href="#">5</a></menu>
<menu><a href="#">6</a></menu>
<menu><a href="#">7</a></menu>
</nav>

2

Answers


  1. For 5 through 7, use :nth-of-type(n+5). The pattern is always An+B, where n starts at 0. So this selects elements 5, 6, 7, …

    See the explanation at https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child#functional_notation

    Example

    menu:hover:nth-of-type(-n+3) {
      background: red;
    }
    menu:hover:nth-of-type(n+5) {
      background: green;
    }
    <nav role="navigation">
      <menu><a href="#">1</a></menu>
      <menu><a href="#">2</a></menu>
      <menu><a href="#">3</a></menu>
      <menu>
        <logo><img src="logo.png"></logo>
        <slogan>slogan here</slogan>
      </menu>
      <menu><a href="#">5</a></menu>
      <menu><a href="#">6</a></menu>
      <menu><a href="#">7</a></menu>
    </nav>
    Login or Signup to reply.
  2. As your 5-7 items are the last once you can use the ‘nth-last-of-type’ selector combined with ‘n’ as follows:

    .menu:hover:nth-last-of-type(-n+3)::after { 
      background: green; 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search