【问题标题】:Why does inner DIV spill out of outer DIV?为什么内部 DIV 会溢出外部 DIV?
【发布时间】:2016-05-27 16:00:18
【问题描述】:

我已经远离 HTML 和 CSS,找不到这个简单问题的解决方案。

我在另一个里面有一个 div。外黑内橙。

我的 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 从外部溢出?如何在不提供固定尺寸的情况下修复它?

【问题讨论】:

  • 把“#inner”的边距去掉,就不会重叠了。
  • @cthefinal 我想有保证金,所以我添加了它。

标签: html css


【解决方案1】:

因为边距 - 宽度是 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>

【讨论】:

    【解决方案2】:

    上面的答案假设您不想要边距。如果您实际上想要边距,那么您可以将overflow: hidden; 添加到#outer。

    【讨论】:

      【解决方案3】:

      您可以将#inner 设置为绝对位置,而不是使用边距,您可以使用它

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

      【讨论】:

        【解决方案4】:

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

        您可以避免使用overflow: hidden; 隐藏任何超出 div 的内容,如果这是您想要做的,否则您需要以不超出其容器的方式设置内部 div 大小

        #outer {
          position: fixed;
          width: 30%;
          height: 30%;
          background-color: black;
          overflow: hidden;
        }
        #inner {
        
          width: 100%;
          height: 100%;
          margin: 5px;
          background-color: orange;
        }
        

        【讨论】:

          【解决方案5】:

          这很可能是因为您的内部 div 被边距推出其父级。您是否尝试将 'inner' 设置为 position: absolute with left: 0 和 top: 0 属性?

          【讨论】:

            猜你喜欢
            • 2011-07-09
            • 1970-01-01
            • 1970-01-01
            • 2010-09-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多