为什么内部DIV会溢出外部DIV?

8

我已经很久没有接触HTML和CSS了,找不到这个简单问题的解决方案。

我有一个div在另一个div里面。外层为黑色,内层为橙色。

enter image description here

我的HTML和CSS如下:

#outer {
  position: fixed;
  width: 30%;
  height: 30%;
  background-color: black;
}
#inner {
  width: 100%;
  height: 100%;
  margin: 5px;
  background-color: orange;
}
<div id="outer">
  <div id="inner">
  </div>
</div>

为什么我的内部DIV溢出外部DIV?如何在不给出固定尺寸的情况下修复它?

从“#inner”中删除边距,它就不会重叠了。 - cthefinal
@cthefinal 我想要有边距,所以我添加了它。 - user3769778
7个回答

8
由于边距的存在,宽度是100%与边距之和。为了避免这种情况,可以写成width: calc(100% - 10px);(等于两倍边距)。高度也一样。

#outer {
  position: fixed;
  width: 30%;
  height: 30%;
  background-color: black;
}
#inner {

  width: calc(100% - 10px);
  height: calc(100% - 10px);
  margin: 5px;
  background-color: orange;
}
<div id="outer">
  <div id="inner">
  </div>
</div>


5
上面的回答假设您不想要边距。如果您实际上需要边距,则可以将overflow: hidden;添加到 #outer 中。

3

margin属性将div向上和向左移动5个像素,由于div默认具有overflow: show;(这意味着任何超出div范围的内容都将显示),因此您可以看到div超出了范围。

如果您想要隐藏任何超出div范围的内容,则可以使用overflow: hidden;,否则您需要设置内部div的大小,以使其不超出其容器。

#outer {
  position: fixed;
  width: 30%;
  height: 30%;
  background-color: black;
  overflow: hidden;
}
#inner {

  width: 100%;
  height: 100%;
  margin: 5px;
  background-color: orange;
}

2
您可以将#inner设置为绝对定位,而不是使用margin,您可以使用以下代码:
#inner {
  position: absolute;
  top: 5px;
  bottom:5px;
  left:5px;
  right:5px;
  background-color: orange;
}

body {
  width: 100%;
  height: 1000px;
}

#outer {
  position: fixed;
  width: 30%;
  height: 30%;
  background-color: black;
}
#inner {
  position: absolute;
  top: 5px;
  bottom:5px;
  left:5px;
  right:5px;
  background-color: orange;
}
<body>
  <div id="outer">
    <div id="inner">
    </div>
  </div>
</body>


1
你可以将元素的内部空间从margin转换为padding,并赋值给#outer
然后,结果将会按照你期望的显示。

#outer {
  position: fixed;
  width: 30%;
  height: 30%;
  background-color: black;
  padding: 5px;
}
#inner {
  width: 100%;
  height: 100%;
  background-color: orange;
}
<div id="outer">
  <div id="inner">
  </div>
</div>


1
这很可能是因为您的内部div受到边距的影响而被推出其父级。您尝试过将“inner”设置为position: absolute,left: 0和top: 0属性吗?

1

我遇到同样的问题时,以下方法对我很有帮助:

position: absolute;
left: 0;
top: 0;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接