如何使现有菜单可滚动

时间:2014-06-28 14:48:58

标签: php html css

如何使菜单中的这个子菜单可滚动,以便它们不会离开屏幕

我的HTML

<nav>
    <ul>
        <li><a href="#">parent</a></li>
        <li><a href="#">parent</a></li>
        <li>
            <a href="#">parent width child</a>
            <ul>
                <li><a href="#">child</a></li>
                <li><a href="#">child</a></li>
                <li>
                    <a href="#">child with children</a>
                    <ul>
                        <li><a href="#">grand child</a></li>
                        <li><a href="#">grand child</a></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li><a href="#">parent</a></li>
    </ul>
</nav>

我的css

/* reset padding and margin where necessary etc. */
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

a {
    text-decoration: none;
}

/* just some quick demo styles for color whatnot */
nav {
    background: black;
    color: white;
}

nav ul ul {
    background: #555;
}

nav ul ul ul {
    background: #999;
}

nav a  {
    color: white;
    white-space:nowrap;
}

nav a:hover  {
    background: #f80;
}

/* important functional styles */
nav > ul:after {
    /* clear the float */
    content:'';
    clear:both;
    display: block;
}

nav li  {
    /* for the topmost level we want them to float.  will be overridden */
    float:left;
}

nav li a {
    /* always apply padding and display block to the a.  better user experience. */
    display:block;
    padding: 10px;
}

nav li ul li {
    /* overridden floating here */
    float: none;
}

/* here is where all the positioning takes place */
nav li {
    position:relative;
}

nav li ul {
    position:absolute;
    left: 0; /* for top most level lets align to the left */
    top: 100%; /* and have it at the bottom of the parent */
    display:none; /* hide initialy */
}

nav li ul li ul {
    left: 100%; /* for grandchild level lets align to the right of the list item */
    top: 0; /* and have it at the top of the parent li */
}

nav ul li a:hover + ul,
nav ul li a + ul:hover {
    /* show only if the element or the immediately preceding anchor is hovered*/
    display:block;
}

/* enjoy! */

请参阅jsfiddle

当有多个子菜单项目或50个这样的项目时,如何使其可滚动?

1 个答案:

答案 0 :(得分:0)

使用overflow-y:scroll;并为第二个<ul>添加高度:

nav li ul li ul {
    left: 100%; /* for grandchild level lets align to the right of the list item */
    top: 0; /* and have it at the top of the parent li */
    height:200px;
    overflow-y:scroll;
}

JSFiddle Example