父元素上的css填充转移子位置

时间:2015-02-04 06:51:04

标签: css position parent-child padding

现在我完全糊涂了。 我已经创建了一个嵌套在父div中的小箭头(带有css),该div已经隐藏了想法,以便在鼠标悬停时将箭头移出一点。 父元素是水平居中的,并且对于(其他一些)好的理由它具有绝对定位。

HTML:

<div id ="arrowContainer">
    <div id="arrow" class="arrow_left"></div>
</div>

CSS:

#arrowContainer {
    position: absolute;
    height: 54px;
    width: 13px;
    bottom: 4.2%;
    left: 50%;
    margin-left: -9px;
    overflow: hidden;
    cursor: pointer;    
}

.arrow_left {
    position: absolute;
    width: 0;
    height: 0;
    padding: 0;
    top: 10px;
    right: -4px;
    border-top: 13px solid transparent;
    border-bottom: 13px solid transparent;
    border-right: 13px solid #fff;
    opacity: 0.72;
}

结果:

enter image description here

确定。现在我想要父母的鼠标悬停区域向侧面延伸一点。我想,好吧,使用一些填充。所以我改变了父母的CSS:

#arrowContainer {
    position: absolute;
    height: 54px;
    width: 13px;
    bottom: 4.2%;
    left: 50%;

    margin-left: -32px;
    padding: 0 24px;

    overflow: hidden;
    cursor: pointer;    
}

这导致了更多意想不到的结果:

enter image description here

1)不仅我必须在一个新的保证金左边值中遇到填充,但是好的,不是那么难做。

2)但为什么我的孩子有权利:-4px值是相对于填充的右边而不是其父母的可见区域(蓝色)定位的?

确定。我知道我可以使用另一个容器来解决这个问题。但这我不想要!必须有一个常规方法来解决这个问题,只有2个div。 这里我的错误是什么?非常感谢!

1 个答案:

答案 0 :(得分:2)

  

但为什么我的孩子有权利:-4px值定位   相对于填充的右边而不是可见区域(蓝色)   其父母的任何更长时间???

不幸的是,填充是如何工作的。填充会在元素内部添加空间,从而移动相对定位元素的外边缘。

但是,这是一个解决方案。而不是使用上,下,左,右使用边距来定位元素。

当您使用position:absolute;添加元素而未设置任何顶部,左侧,右侧或底部位置时,该元素将从正常流程中取出。如果你然后通过修改它的边距来定位它,它就不会受到填充的影响。

JSBin:http://jsbin.com/bowofejuzu/1/edit?html,css,output

HTML:

<div class ="container">
    <div class="element"></div>
</div>

CSS:

.container {
  position:relative;
  width:20px;
  height:100px;
  background-color:#CCC;
  padding:0 40px;  
}

.element {
    position: absolute;
    width: 15px;
    height: 15px;
    background-color:red;

    margin: 40px 0 0 5px;
}
相关问题