• ASP MVC Bootstrap Navigation Dropdowns: Hover on Large Screen, Click on Small

    3.4k Views Asked by At

    I am using the standard Bootstrap class="nav navbar-nav" for navigation with dropdown menus:

    <ul class="nav navbar-nav">
        <li role="presentation" class="@Html.IsSelected("Appointments", "selected")">
            <a data-toggle="dropdown" href="#"><img src="/Content/images/nav_appts.png" style="padding: 0px 5px 3px 0px;">Appointments<span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li>@Html.ActionLink("Appointments Page 1", "Index", "Appointments")</li>
                <li>@Html.ActionLink("Appointments Page 2", "Page2", "Appointments")</li>
            </ul>
        </li>
        // more menu items
    </ul>
    

    Out of the box, the dropdowns only appear if you click on them. I found a way to make them appear if you hover. In the css:

    /* causes the dropdowns to be displayed on-hover instead of on-click */
    ul.nav li.dropdown:hover > ul.dropdown-menu {
        display: block; 
    }
    

    This works great on a standard large screen. But once the screen becomes tablet size, the navigation then switches to the box with bars that drops down to show the nav. Once we get here, I DO NOT want the sub-menu items to appear on hover. I understand that on most tablets, the concept of 'hover' doesn't exist, as there is no mouse. None the less, in case someone is using the site with a very small laptop (etc etc) I want to be able to control this. I tried this:

    @media screen and (max-width: 830px) {
        ul.nav li.dropdown:hover > ul.dropdown-menu {
            display: inline; 
         }
    }
    

    And I played around with a few other options, but I can't seem to get it right.

    1

    There are 1 best solutions below

    1
    artm On BEST ANSWER

    Use two rules with different width so each applies depending on screen size:

    @media screen and (min-width: 831px) {
        ul.nav li.dropdown:hover > ul.dropdown-menu {
            display: block; 
         }
    }
    
    @media screen and (max-width: 830px) {
        ul.nav li.dropdown:hover > ul.dropdown-menu {
            display: inline; 
         }
    }