繁体   English   中英

CSS-如何使div的填充不影响div在其下方的位置

[英]CSS - How to make a div's padding not affect the positioning of the div below it

所以我有两个盒子: https : //jsfiddle.net/anaegm/trajtmgf/

我的初衷是使box-1悬停在其上方时从顶部和底部扩展其高度(而不是通过添加填充来“向下生长”),所以我在:hover下添加了负的margin-top以实现这种效果,并且有效。

问题是,当您将鼠标悬停在box-1上方时,下面的box-2会被下推,并且我需要第二个box始终保持其原始位置。 我尝试在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> 

我为您提供了一个解决方案,但我认为这不是动态的。 看看: https : //jsfiddle.net/trajtmgf/1/

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

使用绝对定位。

 #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> 

我希望这是您正在尝试实现的目标。

不使用定位的另一种方法

 #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 (eg 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM