问题:
我正在尝试创建一个下拉菜单。当输入获得焦点时,它下面的 div 就会出现。但我希望 div 的 z-index 更高。如果 div 的 z-index 较高,则其下方的按钮将被覆盖,但此时 div 不采用任何 z-index。
代码:
我现在正在研究这个例子:
class Main extends React.Component {
render() {
return( <div style={{width: 200}}>
<input className="input" />
<div className="dropdown" style={{ position: 'absolute', zIndex: 9999 }}></div>
<button>Hello</button>
</div>
)
}
}
ReactDOM.render(
<Main></Main>,
document.getElementById('example')
);
这是 CSS:
html, body {
height: 100%
}
body {
background: #333;
font-family: Helvetica Neue;
}
input {
width: 100%;
}
input + div.dropdown {
background-color: #ffff00;
display: none;
height: 200px;
width: 100%;
}
input:focus + div.dropdown {
display: flex;
}
这是相同代码的插件:
https://plnkr.co/edit/B8Kjhv6rUOv0s7QKotxI?p=preview
我尝试了什么:
如果我将下拉 div 的位置更改为绝对位置,则会应用 z-index,但 div 的宽度等于屏幕宽度。
我正在创建一个可重复使用的组件,所以我不能给出固定的宽度。
注意:
main div 的固定宽度只是一个例子,在实际使用中,main div 的宽度将由其父组件的 100% 宽度自动确定。
最佳答案
总结:
声明position relative
在包含(父)元素上允许对绝对定位兄弟元素的 width
进行控制。 .
关于定位元素和堆叠上下文:
处理定位元素和堆叠上下文时需要考虑的几件事:
-
z-index
属性值将仅适用于定位 元素。 - positioned 元素是带有
position
的元素属性值定义为absolute
,fixed
,relative
或者sticky
experimental ;这不包括static
, 任何元素的默认定位。 - 将元素声明为绝对定位元素时
(
absolute
或fixed
)您正在从 自然文档流;这仅仅意味着该元素不再是 以relative
的方式与兄弟元素交互或static
元素做(想象一下元素“位于”DOM 的其余部分之上)。 - 默认情况下,绝对定位元素的位置是
“相对于”窗口;这意味着如果你偏移它的位置
与
left
或right
它将移动的距离等于属性值 来自窗口的属性值。您可以定位一个元素 用position
absolute
的属性(property)值(value)(不是fixed
)相对 到任何包含元素 如果你声明相对定位到 包含元素。 这是您在用例中观察到的问题;自从 嵌套
.dropdown
元素被定位absolute
它被取出了 的自然流动并占据了整个可用宽度 包含文件,所以为了限制它的宽度 包含元素,position: relative
应在其上声明 包含元素,例如:<div style="width:200px;position: relative;" data-reactid=".0"> <input class="input" data-reactid=".0.0"> <div class="dropdown" style="position:absolute;z-index:9999;" data-reactid=".0.1"></div> <button data-reactid=".0.2">Hello</button> </div>
将类选择器也赋予该元素可能会更好(并且更可调用),这样您就可以在外部使用其他声明的样式(在 style.css 中)管理和维护这些样式,例如:
已修改html
结构:
<div class="foobar" data-reactid=".0">
<input class="input" data-reactid=".0.0">
<div class="dropdown" style="position:absolute;z-index:9999;" data-reactid=".0.1"></div>
<button data-reactid=".0.2">Hello</button>
</div>
附加 css
声明:
.foobar {
width:200px;
position: relative; /* required for nested absolute element */
}
引用:
关于css - 如何设置下拉div的z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48195709/