2016-11-03 38 views
0

所以,我有两个箱子的div定位: https://jsfiddle.net/anaegm/trajtmgf/CSS - 如何让一个div的填充不会影响它下面

我的初衷是为了让box-1从顶部和底部扩大它的高度,当你徘徊(而不是仅仅通过添加填充来“增长”),所以我在:hover下添加了一个负边界顶点以实现此效果,并且它可以工作。

问题是box-2在您悬停在box-1以上时被推下,我需要第二个盒子始终保持原来的位置。我尝试在box-2的顶部添加一个边距,但这不起作用。我有什么选择?

编辑:因为我正在为我正在做的实际页面的动态文本工作,所以我宁愿不使用设置高度为box-1的div容器。

#box-1 { 
 
    color: #fff; 
 
    background-color: #e91d23; 
 
    text-align: center; 
 
    cursor: pointer; 
 
    width: 100px; 
 
    padding-top: 30px; 
 
    padding-bottom: 30px; 
 
} 
 
#box-1:hover { 
 
    background-color: #5A5A5A; 
 
    margin-top: -10px; 
 
    padding-top: 40px; 
 
    padding-bottom: 40px; 
 
} 
 
#box-2 { 
 
    width: 100px; 
 
    background-color: white; 
 
    text-align: center; 
 
    padding-top: 30px; 
 
    padding-bottom: 30px; 
 
    margin-top: 50px; 
 
}
<div id="box-1"> 
 
    Box 1 
 
</div> 
 
<div id="box-2"> 
 
    Box 2 
 
</div>

+1

另一种方法如何设置绝对位置的元素?这样他们的元素将不会互相干扰 –

+0

绝对位置是一种矫枉过正 – arhak

回答

1

使用绝对定位。

#box-1 { 
 
    position: absolute; 
 
    color: #fff; 
 
    background-color: #e91d23; 
 
    text-align: center; 
 
    cursor: pointer; 
 
    width: 100px; 
 
    padding-top: 30px; 
 
    padding-bottom: 30px; 
 
} 
 
#box-1:hover { 
 
    background-color: #5A5A5A; 
 
    margin-top: -10px; 
 
    padding-top: 40px; 
 
    padding-bottom: 40px; 
 
} 
 
#box-2 { 
 
    position: absolute; 
 
    width: 100px; 
 
    background-color: white; 
 
    text-align: center; 
 
    padding-top: 30px; 
 
    padding-bottom: 30px; 
 
    top: 100px; 
 
}
<div id="box-1"> 
 
    Box 1 
 
</div> 
 
<div id="box-2"> 
 
    Box 2 
 
</div>

我希望这是你试图实现。

+0

您的评论后,我曾尝试绝对定位,但我完全错过了使用顶级属性。谢谢。 –

+0

乐意提供帮助。 –

1

我要给你一个这样的解决方案,但我认为这不是动态的。看看:https://jsfiddle.net/trajtmgf/1/

#box-1:hover + #box-2{ 
    margin-top: 40px; 
} 
1

不使用定位

#box-1 { 
 
    color: #fff; 
 
    background-color: #e91d23; 
 
    text-align: center; 
 
    cursor: pointer; 
 
    width: 100px; 
 
    margin-top: 10px; 
 
    padding-top: 30px; 
 
    padding-bottom: 30px; 
 
    margin-bottom: 10px; 
 
} 
 
#box-1:hover { 
 
    background-color: #5A5A5A; 
 
    margin-top: 0; 
 
    padding-top: 40px; 
 
    padding-bottom: 40px; 
 
    margin-bottom: 0px; 
 
} 
 
#box-2 { 
 
    width: 100px; 
 
    background-color: white; 
 
    text-align: center; 
 
    padding-top: 30px; 
 
    padding-bottom: 30px; 
 
} 
 
#avoid-margin-collapse { 
 
    /* avoid margin collapse (e.g. with a border, a padding, position) */ 
 
    padding: 1px; 
 
}
<div id="avoid-margin-collapse"> 
 
<div id="box-1"> 
 
    Box 1 
 
</div> 
 
<div id="box-2"> 
 
    Box 2 
 
</div> 
 
</div>