我一直在学习从this w3schools example做一个基本的下拉菜单。据说我们可以通过将min-width
设置为100%来更改下拉内容的宽度。它工作得很好。但是,如果我将position: relative
更改为position: static
,则下拉内容最终会占据窗口宽度的100%。 AFAIK width: 100%
应将宽度设置为父容器的100%。将父容器的位置更改为静态不会改变它的宽度,因此子项不应分布在父容器中。以下是我正在尝试的代码:
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown {
position: static;
display: inline-block;
border: 2px solid red;
}
.dropdown-content {
display: none;
position: absolute;
background-color: grey;
min-width: 100%;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
</body>
</html>
&#13;
- 那么,为什么为
position-static
类(或一般的父元素)设置.dropdown
会导致.dropdown-content
类元素(或一般的子元素)具有全屏宽度而不是宽度与父容器的宽度相同?
附录:似乎静态定位父级的绝对定位子项占据视口的整个宽度。例如。以下代码:
<DOCTYPE html>
<html>
<head>
<style>
div#one{border: 2px dotted red; position: static; width:100px;}
div#two{border: 2px solid blue; width:100%; position: absolute;}
</style>
</head>
<body>
<div id="one">
Text of statically positioned box
<div id="two"> Text of absolutely positioned box.</div>
</div>
</body>
</html>
&#13;
蓝色框分布在整个视口中,位于具有红色边框的父容器之外。为什么会这样?
答案 0 :(得分:1)
Static
是页面上任何元素的默认行为。因此,当您将.dropdown-content
的位置设为absolute
时,它会根据最近的相对定位父级设置其宽度,在您的情况下,视口为“否”其他元素相对定位。
但是,您将.dropdown
定位为相对,.dropdown-content
为绝对,.dropdown-content
(.dropdown
的子项)的移动距离最近的< strong>相对定位父级(.dropdown
),这就是.dropdown-content
在父级(.dropdown
)静态定位时占据全宽的原因
.dropdown {
position: static;
display: inline-block;
border: 2px solid red;
}
.dropdownRelative {
position: relative;
display: inline-block;
border: 2px solid red;
}
.dropdown-content {
display: none;
position: absolute;
background-color: grey;
min-width: 100%;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 2;
}
.parent{
position: relative;
margin-top:20px;
width: 400px;
border: 2px solid red;
}
.dropdown:hover .dropdown-content,.dropdownRelative:hover .dropdown-content,.parent:hover .dropdown-content {
display: block;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>I am statically positioned and parent as static.</p>
</div>
</div>
<div class="dropdownRelative">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>I am absolutely positioned and my parent is relatively positioned</p>
</div>
</div>
<div class="parent">
<span>Hover over me</span>
<div class="dropdown-content">My parent is relatively positioned!</div>
</div>
</body>
</html>
&#13;