2个div位于绝对位置,1个位阻挡另一个

时间:2014-07-17 17:31:22

标签: html css position center absolute

我有2个div,两个都有相同的宽度,位于页面的水平和垂直方向的绝对位置。

每个div都包含一个链接。但是只能点击一个链接。我需要两个链接都可以点击。

这是我的jsfiddle

<div class="button"> <a href="http://www.google.com" target="_blank">button</a> </div>
<div class="arrows"> <a href="http://www.google.com" target="_blank">arrows</a> </div> 

.button, .arrows {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 520px;
 height: 240px;
 margin: auto !important; 
 border: 1px solid #000;
}
.button { z-index: 999; }
.arrows { text-align: center; z-index:99999; }
.button a { border: 1px solid red; }
.arrows a { border: 1px solid yellow; }

任何提示都会得到真正的赞赏。

谢谢。

3 个答案:

答案 0 :(得分:1)

问题是两个div占据了整个盒子的空间,因此两者都不可能被点击。

解决方案是使用一个div容器作为框,并使按钮和箭头a成为容器中较小的元素:

<div class="container">
    <a class="button" href="http://www.google.com" target="_blank">button</a>
    <div class="arrow"><a href="http://www.google.com" target="_blank">arrows</a></div>
</div>

为了保持相同的外观,我们需要一个箭头容器,它将箭头的链接居中。按钮链接为position: absolute,以允许两个链接存在于同一行。

.container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 520px;
    height: 240px;
    margin: auto !important;
    border: 1px solid #000;
}
.arrow {
    display: inline-block;
    width: 100%;
    text-align: center;
}
.arrow a {    
    border: 1px solid yellow;
}
.button {
    border: 1px solid red;
    position: absolute;
}

查看更新的 Fiddle

答案 1 :(得分:0)

问题源于你将div设置为相同的宽度和高度,第二个div覆盖了第一个div,因此点击不会失败。

如果你想要那个边框,你需要一个父div。

的jsfiddle http://jsfiddle.net/6qXAm/

<div class="parent">
<div class="button"> <a href="http://www.google.com" target="_blank">button</a> </div>
<div class="arrows"> <a href="http://www.google.com" target="_blank">arrows</a> </div>    
</div>

.parent {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 520px;
    height: 240px;
    margin: auto !important; 
    border: 1px solid #000;
}

答案 2 :(得分:0)

好的,我要发布另一个答案,因为这个方法采用了完全不同的方法。

CSS允许使用属性pointer-events,它允许您指定元素是否可以成为鼠标事件的主题。

在这种情况下,您不希望.arrows div维持鼠标事件,但执行需要.arrows a链接元素。所以你会使用:

.arrows { pointer-events: none; }
.arrows a { pointer-events: all; }

这将允许点击链接,但对于div的其余部分,会强制鼠标事件(点击)通过到其下的元素(在这种情况下, .buttons链接)。

这是一种黑客行为,但效果很好 请参阅 Fiddle

相关问题