【问题标题】:css padding on parent element shifts child position父元素上的 css 填充移动子位置
【发布时间】:2015-04-03 14:36:10
【问题描述】:

现在我完全糊涂了。 我创建了一个嵌套在父 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;
}

结果:

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

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

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

    overflow: hidden;
    cursor: pointer;    
}

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

1) 不仅我必须在新的 margin-left 值中遇到填充,而且还可以,并不难做到。

2) 但是为什么我的孩子有 right: -4px 值相对于填充的右侧而不是其父级的可见区域(蓝色)?

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

【问题讨论】:

  • 尝试right:20px 定位箭头。
  • #arrowContainer { 填充:0 24px; },这将您的箭头向右推,尝试使用边距。一个 JSFiddle 在这里会很好。
  • 尝试删除right:-4px jsfiddle.net/yggc3tfn
  • 谢谢大家!我看到填充物将 cild 推到了右边。我的问题是:为什么?我一直认为 right 是指 div 的右边框而不是它的填充边缘。不能这样使用时,填充有什么意义?
  • padding 也被认为是widthheight 例如如果你设置一个div的宽度并添加padding到宽度会增加

标签: css position parent-child padding


【解决方案1】:

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

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

但是有一个解决方案。不要使用顶部、底部、左侧、右侧,而是使用 ma​​rgin 来定位您的元素。

当您使用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;
}

【讨论】:

  • 啊。而且我一直认为填充是在元素之外添加的。奇怪的。是时候学会了!也感谢大家的提琴!我觉得这里需要的是一种外部边界。或许这个方向也有解决方案(保持上、下、左、右……)不过到目前为止非常感谢大家!
猜你喜欢
  • 2017-03-06
  • 2023-03-10
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
相关资源
最近更新 更多