Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

html - CSS drop down menu hover effect

i was trying to make a simple css drop down menu. I'm not able to achieve the drop down sub menu when you hover over a link. Below is my html and css rule, thanks.

    ul#menu li
    {
        position:relative;
        list-style-type:none;
        float: left;
        padding:0px;
        width: 125px;
        height: 25px;
    }
    ul#sub1 li
    {
        position:absolute;
        left:0;
        width:125px;
        visibility: hidden;
    }
    ul#menu li:hover #sub1
    {
        visibility:visible;
    }


    <ul id="menu">
        <li><a href="#">Hyperlink 1</a></li>
        <li><a href="#">Hyperlink 2</a>
            <ul id="sub1"> 
                <li><a href="#">Hyperlink 2.1</a></li>
                <li><a href="#">Hyperlink 2.2</a></li>
            </ul>
        </li>
        <li><a href="#">Hyperlink 3</a></li>
        <li><a href="#">Hyperlink 4</a></li>
    </ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

ul#sub1 {
    position:absolute;
    left:0;
    width:125px;
    visibility: hidden;
}
ul#menu li:hover #sub1 {
    visibility:visible;
}

Fiddle

issue is that your your menu ul is visible (always) but the li's inside them are invisible (always) due to the selector of the this rule ul#sub1 li.

Do remember that visibility:hidden hides the element but still occupies space in DOM, whereas display:none hides the element and takes it out of page element flow

Also you necessarily do not need to use ids in css selectors especially for a menu like this. You can achieve it without that, consider the situation with many level menus, by using ids you will have to write selectors indefinitely. Instead you can try something like this.

ul#menu ul {
    padding:0px;
}
ul#menu li {
    position:relative;
    list-style-type:none;
    float: left;
    width: 125px;
}
ul#menu li > ul {
    display: none;
}
ul#menu li:hover > ul {
    display:block;
}

Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...