如何在使用overflow:hidden的Div上方放置一个按钮?

4

我有一个方框,想把按钮放在方框上面。

我已经尝试过使用z-index、grid-content等方法,但是按钮没有显示在上方,按钮必须在方框内部。

Html:

#content {
    width: 300px;
    height: 100px;
    overflow: hidden;
    position: relative;
    background: orange;
}

input[type='button'] {
    position: absolute;
    right: -30px;
}
<div id="content">
    <input type="button" value="Click me!" />
</div>

我希望按钮覆盖在方框之上,而不是按钮必须在方框内部。


1
你能详细说明一下吗? - Sree Nath
你可以直接运行代码片段,然后看到问题:按钮仍然在盒子内部,没有超出盒子。 - Rampage Programming
4个回答

5

你可以尝试像这样。

#content {
width: 300px;
    height: 100px;
        position: relative;
    }
#box{
width: 300px;
    height: 100px;
    overflow: hidden;
    position: relative;
    background: orange;
}
input[type='button']{
position: absolute;
    right:-30px;
    z-index:1000;
    float: right;
    top: 20px;
}
<div id="content">
  <div id="box">
  </div>
  <input type="button" value="Click me!" />
</div>


那就是我一直在寻找的答案,非常感谢你。 - Rampage Programming

1

问题在于您的按钮位置相对于父元素#content,因此无法显示在外部。要解决这个问题,您需要删除overflow:hidden或者去掉#content上的position:relative

或者您可以将您的

包装在另一个
中,如下所示:

#content{
width: 300px;
    height: 100px;
    overflow: hidden;
    background: orange;
}
input[type='button']{
position: absolute;
    right:-30px;
}
.mainparent{
      position: relative;
  width:fit-content;
}
<div class="mainparent">
<div id="content">
<input type="button" value="Click me!" />
</div>
</div>

the .mainparent div will take same height and width as #content div but with no overflow:hiiden


它必须被隐藏。 - Rampage Programming
@RampageProgramming,你的内容div被隐藏了,但是mainparent div没有! - adel

0

当设置 overlow 属性为 hidden 时,只有一种选择:对按钮使用 position: fixed 并相对于窗口应用定位。请注意,在滚动时需要重新调整位置。

#content{
width: 300px;
    height: 100px;
    overflow: hidden;
    position: relative;
    background: orange;
}
input[type='button']{
    position: fixed;
    right:290px;
}
<div id="content">

<input type="button" value="Click me!" />
</div>


0

right: -30px会将按钮放在盒子外面。试试这个:

<html>

<head>
    <style>
        #content {
            width: 300px;
            height: 100px;
            overflow: hidden;
            position: relative;
            background: orange;
        }

        input[type='button'] {
            position: absolute;
            right: 30;
        }
    </style>
</head>

<body>
    <div id="content">
        <input type="button" value="test">
    </div>
</body>

</html>

它必须超过这个框。 - Rampage Programming

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接