Search code examples
cssmedia-queriesstyling

CSS Media Query not displaying desired output


When the viewport is larger than 992px, I'd like to display a grey line under the menu elements in the following two instances:

  1. When a page is being actively visited, I want the line to stay in place
  2. When a page is not being actively visited, I want the line to appear upon hovering

Here's my code (as instructed by Code Institute):

General styling

/* Nav bar */

.active {
    border-bottom: 1px solid #3a3a3a;
}

Media Query

/* Media Query: laptops and desktops (992px and up) */
@media screen and (min-width: 992px) {
    #menu a:hover {
        border-bottom: 1px solid #3a3a3a;
    }
}

Edit: the :hover selector is working, but the line isn't staying in place upon actively visiting each page.

I'm quite new to CSS and web development overall, so I tried removing the general styling to see if the media query would work as expected. It did. I also tried adding an :active selector to the general styling, but that didn't work. Beyond those two things, I'm not entirely sure how to troubleshoot the issue, hence my question.

Thanks!


Solution

  • You can read how to use hover together with media queries from this MDN docs (CCS4 convention) .

    Here is an example of how you can use hover inside media queries.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>News</title>
        <style>
          @media screen and (min-width: 992px) and (hover: hover) {
            #menu a:hover {
              border-bottom: 1px solid #3a3a3a;
            }
          }
        </style>
      </head>
      <body>
        <div id="menu">
          <a href="#">Try hovering over me! I get underline on Hover</a>
        </div>
        <div>
          <a href="#">Hovering over me doesn't apply style</a>
        </div>
      </body>
    </html>
    

    As for your case (based on your code from link in comments):

    1. case where you want "actively visited". You have to use either :active selector or :visited selector based on your need.
      Currently your code has a class="visited" applied to all your links, which gives you the content of .visited permanently. If you use selector you will get desired output.

      I think you want to toggle between the links and show page below based on what is selected. I would recommend you use any scripting language to achieve that. Since it would be much easier. Refer to some navbar code's since you are new.

    2. due to .visited having same code as hover you were not able to see any changes on hover. If you comment .visited or change it to an appropriate selector. It will work for you.