我想制作一个包含HTML / CSS和一些javascript的下拉菜单。我坚持使用li元素的宽度。它必须具有内部宽度而不是静态宽度。
问题是当我将鼠标悬停在li元素上时(为了显示下拉菜单),它正在改变他的宽度。
我创建了一个jsfiddle文件,您可以找到here.
CSS:
#nav{
background-color: #1da8d8;
width: 100%;
max-width: 960px;
margin: 0;
padding: 0;
float: left;
}
#nav li a i {
text-align: right;
}
#nav ul {
padding: 0;
margin:0;
list-style: none;
width:12em;
z-index:99;
position:relative;
overflow:visible;
}
#nav li {
background-color: #1b9cc9;
position: relative;
line-height: 39px;
height: 40px;
width: auto;
margin: 0 5px 0 0;
float:left;
display:block;
}
#nav ul li{
background-color:#1b9cc9;
top: 20px;
width: 12em;
float: left;
}
#nav a {
color: #ffffff;
text-decoration:none;
display:block;
padding: 0.1em;
margin: 0 0.2em 0 0;
height:1.05em;
width: auto;
}
#nav ul li:hover, #nav ul li a:hover{ background-color:#1da8d8;}
#nav ul{
display:none;
}
/*all see this */
#nav ul ul, #nav ul ul ul{
display:none;
position:absolute;
margin-left:12em;
}
/* non-IE browsers see this */
#nav ul li>ul, #nav ul ul li>ul{
margin-top:-1.8em;
}
#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li:hover ul ul ul ul, #nav li:hover ul ul ul ul ul{
display:none;
}
#nav li:hover ul, #nav ul li:hover ul, #nav ul ul li:hover ul, #nav ul ul ul li:hover ul, #nav ul ul ul ul li:hover ul{
display:block;
}
li>ul {
top: auto;
left: auto;
}
答案 0 :(得分:5)
宽度现在自动调整到孩子的整个宽度。将孩子的位置设置为绝对会忽略这一点。
将postition:relative;
上的#nav ul
更改为position:absolute;
#nav ul {
padding: 0;
margin:0;
list-style: none;
width:12em;
min-width:100%;
z-index:99;
position:absolute;
overflow:visible;
}
答案 1 :(得分:1)
你也需要在这里明确设置宽度和最大宽度 - 在你的CSS中试试这个
#nav li {
background-color: #1b9cc9;
position: relative;
line-height: 39px;
height: 40px;
width: 12em;
max-width: 12em;
margin: 0 5px 0 0;
float:left;
display:block;
}