所以我有两个盒子: https://jsfiddle.net/anaegm/trajtmgf/
我的初衷是让box-1
在你徘徊时从顶部和底部扩展它的高度(而不仅仅是#34;通过添加填充来增长#34},所以我添加了一个负边缘 - 顶部:悬停以实现此效果,并且有效。
问题是,当您将鼠标悬停在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>
&#13;
答案 0 :(得分:1)
我有一个解决方案,但我认为这不是动态的。看看:https://jsfiddle.net/trajtmgf/1/
#box-1:hover + #box-2{
margin-top: 40px;
}
答案 1 :(得分: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>
我希望这是你想要实现的目标。
答案 2 :(得分: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>