首页 > 解决方案 > 为什么这个 CSS 代码在我的内盒中溢出,即使它适合我的外盒?

问题描述

所以我创建了一个带有 2 个 div 标签的盒子,即:外层 div 和盒子 div。

我的外部 div 的总宽度(内容块)为 600w+50padLeft+50padRight=700px。同时我的盒子 div(包含块)的总宽度是 500w+98padL+98padR+4border = 700px。

然而,我的盒子在外部 div 中溢出了。

这是图片: https ://www.flickr.com/photos/183721425@N02/48599642452/in/dateposted-public/

aside,
article,
section,
header,
footer,
nav {
  display: block;
}

div,
p {
  margin: 0;
  padding: 0;
}

html {
  background: #ccc;
}

.outer {
  /* TOTAL WIDTH: 700px */
  width: 600px;
  margin: 0 auto;
  background: #9CF;
  padding: 50px;
}

.box {
  background: #B7D19C;
  /* TOTAL WIDTH: 700px */
  width: 500px;
  padding: 98px;
  border: 2px black solid;
}

p {
  background: #FF9;
  height: 100%;
  /* here */
}
<div class="outer">
  <div class="box">
    <p>Here we'll need to calculate the width of this interior div element. This may seem simple at first, but as we begin to add box model properties, and as the overall width of the parent element and the div conflict with one another, we'll need to understand
      how each of the properties combine to effect the overall width (and height) of page elements.
    </p>
  </div>
</div>

标签: cssoverflow

解决方案


使用box-sizng:border-box财产。

它定义了如何计算元素的宽度和高度,它们是否包括填充和边框。不考虑保证金。通常元素的大小(宽度或高度)不包括边框或填充

*{
box-sizing: border-box;
}
<!DOCTYPE HTML>
<html>

<head>
  <meta charset="UTF-8">
  <title>calculating element dimensions</title>
  <!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
  <style>
    aside,
    article,
    section,
    header,
    footer,
    nav {
      display: block;
    }
    
    div,
    p {
      margin: 0;
      padding: 0;
    }
    
    html {
      background: #ccc;
    }
    
    .outer {
      /* TOTAL WIDTH: 700px */
      width: 600px;
      margin: 0 auto;
      background: #9CF;
      padding: 50px;
    }
    
    .box {
      background: #B7D19C;
      /* TOTAL WIDTH: 700px */
      width: 500px;
      padding: 98px;
      border: 2px black solid;
    }
    
    p {
      background: #FF9;
      height: 100%;
      /* here */
    }
    /*add styles here*/
  </style>
</head>

<body>
  <div class="outer">
    <div class="box">
      <p>Here we'll need to calculate the width of this interior div element. This may seem simple at first, but as we begin to add box model properties, and as the overall width of the parent element and the div conflict with one another, we'll need to
        understand how each of the properties combine to effect the overall width (and height) of page elements.
      </p>
    </div>
  </div>
</body>

</html>


推荐阅读