首页 > 解决方案 > (margin/padding)-right 不会为溢出容器创建空间

问题描述

由于某种原因,在溢出的容器中,右侧的填充没有显示。

.parent {
  background-color: orange;
  width: 150px;
  height: 50px;
  overflow: auto; 
  padding-right: 15px;
}

.child {
  background-color: blue;
  width: 250px;
  height: 100%;
  margin: 0 10px;
}

body {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}
<div class="parent">
  <div class="child">
  </div>
</div>

我希望滚动到最后时会出现橙色(右)

标签: htmlcss

解决方案


让我们从不应用任何overflow属性开始。我们显然在它的父容器之外有元素(添加容器的填充将保留在里面):

.parent {
  background-color: orange;
  width: 150px;
  height: 100px;
  padding:15px;
}

.child {
  background-color: blue;
  width: 250px;
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}
<div class="parent">
  <div class="child">
  </div>
</div>

在此处输入图像描述

现在通过添加overflow:scrolloroverflow:auto您只需添加滚动即可查看溢出部分,并且您不会将填充视为例外:

.parent {
  background-color: orange;
  width: 150px;
  height: 100px;
  overflow:auto;
  padding:15px;
}

.child {
  background-color: blue;
  width: 250px;
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}
<div class="parent">
  <div class="child">
  </div>
</div>

在此处输入图像描述

与右边距相同的逻辑。当元素溢出时,没有空间在内部元素和父元素之间添加边距。


推荐阅读