CSS dropdown menu with submenu aligning to the right edge of it's parent

后端 未结 5 648
执念已碎
执念已碎 2020-12-30 08:15

Here is a very easy example of CSS based dropdown menu: http://jsfiddle.net/V8aL6/

    
相关标签:
5条回答
  • 2020-12-30 08:36

    To automatically make dropdowns on the right align right:

    <script>
    // make dropdowns on the right align right, etc, so they don't go off screen
    var dropdown_uls = document.querySelectorAll('#nav li ul')
    function fix_dropdowns(){
        for (var i=0; i< dropdown_uls.length; i++) {
            var ul = dropdown_uls[i]
            var rect = ul.getBoundingClientRect()
            var body = document.body.getBoundingClientRect()
            if(rect.right > body.right){
                ul.style.left = 'auto'
                ul.style.right = 0
            }
            if(rect.left < body.left){
                ul.style.left = 0
                ul.style.right = 'auto'
            }
        }
    }
    fix_dropdowns()
    addEventListener('resize', fix_dropdowns)
    </script>
    
    0 讨论(0)
  • 2020-12-30 08:37

    Add the Bootstrap class .pull-right to <div class='btn-group'. Should look like below: <div class='btn-group pull-right'

    0 讨论(0)
  • 2020-12-30 08:38

    Its better and more clean if you position your list to the right and instead of moving UL out of the screen you could just toggle the display property from none to block.

    You will need to make some changes in these rules and add those properties:

    #nav li:hover ul {
        display: block;
        right: 0;
    }
    
    #nav ul {
        display: none;
    }
    #nav ul li {
        margin-right: 0;
    }
    

    See my updated fiddle: http://jsfiddle.net/V8aL6/2/

    0 讨论(0)
  • 2020-12-30 08:48

    A better solution should be:

    #nav ul li ul, #nav ul li:hover ul {
        float:right;
        margin-right:2px; /*optional*/
    }
    
    0 讨论(0)
  • 2020-12-30 08:57

    This menu achieves the hiding/showing by modifying the left property. All you need is to adapt the CSS-rule which steers the show mechanism for the submenu:

    #nav li:hover ul{
        left:0;
    }
    

    instead of aligning it to the left, we want to align it right, so we add right:0;. However, if we do not touch the left declaration, the menu will get cut off, so instead of left:0; we write left:auto; to let the menu expand to it's intrinsic width. To accomodate for the margin of the parent li, we add the same amount as negative margin and we are done:

    #nav li:hover ul{
        left:auto;
        right:0;
        margin-right:-10px;
    }
    

    you modified fiddle

    0 讨论(0)
提交回复
热议问题