我有一个包含一些调整大小元素的列表。当调整元素大小时,它们应该在 x 方向溢出容器。永远不应该在 x 方向上滚动。应在 y 方向启用滚动。
我尝试过设置:
overflow-x: visible;
overflow-y: scroll;
Run Code Online (Sandbox Code Playgroud)
但这似乎可以双向滚动。
我该如何防止这种情况?
https://jsfiddle.net/64tw8rqe/
CSS溢出-x的答案:可见;和溢出-y:隐藏;导致滚动条问题解释了根本问题,但不是scroll.
此行为符合规范。我正在寻找解决方法。
问题是这overflow-x: visible; overflow-y: scroll在 CSS 中是不可能的组合。每当visible与 配对时scroll,它都会转换为auto.
换句话说,这些是等效的:
overflow-x: visible;
overflow-y: scroll;
overflow-x: auto;
overflow-y: scroll;
Run Code Online (Sandbox Code Playgroud)
对于规范来说,这也许是一个糟糕的决定,但有解决方法。
通过制作扩展元素position: absolute,它们的大小不会改变容器,并且它们不会被 裁剪overflow: hidden。为了使它们正确定位,在整个容器周围缠绕了一个额外的div带子。position: relative
HTML:
<div class='container1'>
<div class='container2'>
<ul class='messages'>
<li><pre>Hello</pre></li>
<li>
<pre>This is a
really really really
really really long message.</pre>
</li>
<li><pre>World</pre></li>
</ul>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
* {
margin: 0;
padding: 0;
}
.container1 {
position: relative;
width: 200px;
}
.container2 {
background: #f0f;
width: 100%;
height: 100%;
overflow: scroll;
}
.messages {
overflow: visible;
list-style: none;
}
.messages li {
background: #ff0;
width: 100%;
height: 24px;
margin-top: 12px;
}
.messages li pre {
position: absolute;
display: inline-block;
box-sizing: border-box;
width: 100%;
max-height: 24px;
padding: 4px;
background: #0ff;
border-radius: 4px;
line-height: 16px;
overflow: hidden;
text-overflow: ellipsis;
width: auto;
min-width: 100%;
max-width: 100%;
transition: max-width 200ms ease-out, height 200ms ease-out;
}
.messages li pre:hover {
z-index: 1;
background: #00f;
max-width: 80vw;
max-height: 80vh;
transition: max-width 200ms ease-in, max-height 200ms ease-in;
}
Run Code Online (Sandbox Code Playgroud)
小提琴: https: //jsfiddle.net/cyL6tc2k/2/
归功于这里发现的技巧:http://front-back.com/how-to-make-absolute-positioned-elements-overlap-their-overflow-hidden-parent