【发布时间】:2022-03-26 23:05:12
【问题描述】:
虽然我一直在学习有关 CSS 的更多信息,但我一直在查看 post on creating a drop-down menu 和 code demo 这里。
阅读position: absolute; 的行为方式应如CSS specification 中所述,它指出:
在绝对定位模型中,一个盒子相对于它的包含块显式地偏移。它完全从正常流程中移除(对后面的兄弟姐妹没有影响)。
containing block 是这样确定的:
如果元素具有'position: absolute',则包含块由最近的具有非静态位置的祖先建立...如果没有这样的祖先,则包含块是初始包含块。
在菜单上的链接帖子中,它没有解释在这种情况下绝对定位是如何工作的。首先,没有偏移来定位元素。而且,除非我遗漏了什么,在我看来,除了默认的position: static;
我的期望不是使用position:absolute; 的下拉菜单会作为下拉菜单的一部分出现,而是应该相对于页面定位,因此可能会出现在左上角,完全不在流。
我的假设是错误的。那么,父菜单项正下方的定位是如何解释的呢?
HTML:
<body class="news">
<header>
<div class="nav">
<ul>
<li class="home"><a href="#">Home</a></li>
<li class="tutorials"><a href="#">Tutorials</a>
<ul>
<li><a href="#">Tutorial #1@@</a></li>
<li><a href="#">Tutorial #2</a></li>
<li><a href="#">Tutorial #3</a></li>
</ul>
</li>
<li class="about"><a class="active" href="#">About</a></li>
<li class="news"><a href="#">Newsletter</a>
<ul>
<li><a href="#">News #1</a></li>
<li><a href="#">News #2@@@</a></li>
<li><a href="#">News #3</a></li>
</ul>
</li>
<li class="contact"><a href="#">Contact</a></li>
</ul>
</div>
</header>
</body>
CSS:
body {
margin: 0;
padding: 0;
background: #ccc;
}
.nav ul {
list-style: none;
background-color: #444;
text-align: center;
padding: 0;
margin: 0;
}
.nav li {
font-family: 'Oswald', sans-serif;
font-size: 1.2em;
line-height: 40px;
text-align: left;
}
.nav a {
text-decoration: none;
color: #fff;
display: block;
padding-left: 15px;
border-bottom: 1px solid #888;
transition: .3s background-color;
}
.nav a:hover {
background-color: #005f5f;
}
.nav a.active {
background-color: #aaa;
color: #444;
cursor: default;
}
/* Sub Menus */
.nav li li {
font-size: .8em;
}
/*******************************************
Style menu for larger screens
Using 650px (130px each * 5 items), but ems
or other values could be used depending on other factors
********************************************/
@media screen and (min-width: 650px) {
.nav li {
width: 130px;
border-bottom: none;
height: 50px;
line-height: 50px;
font-size: 1.4em;
display: inline-block;
margin-right: -4px;
}
.nav a {
border-bottom: none;
}
.nav > ul > li {
text-align: center;
}
.nav > ul > li > a {
padding-left: 0;
}
/* Sub Menus */
.nav li ul {
position: absolute;
display: none;
width: inherit;
}
.nav li:hover ul {
display: block;
}
.nav li ul li {
display: block;
}
}
【问题讨论】:
标签: html css drop-down-menu html-lists