向 div 添加边距会将其推离屏幕

Adding margin to div pushes it off the screen

我想在我的每个 div 周围留出 5px 的边距,但是当我在 CSS 中添加它时,除 div 之间和底部外,每边都有 5px 的边距。这两个 div 也从页面底部溢出。我知道这是因为顶部的 5px 边距将 div 推离了屏幕。我不确定如何让它只是在周围添加边距并相应地缩小 div。

* {
  box-sizing: border-box;
  margin: 0;
}

html {
  width: 100%;
  height: 100%;
}

body {
  background: black;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.one {
  background: red;
  position: absolute;
  width: 10%;
  height: 100%;
  left: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}

.two {
  background: blue;
  position: absolute;
  width: 90%;
  height: 100%;
  right: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}
<div class="one">
</div>
<div class="two">
</div>

Resulting Page

Divs 在底部推离屏幕并且 div 之间没有边距。存在顶部、左侧和右侧 5 像素的边距。

我是 HTML 和 CSS 的新手,所以非常感谢任何帮助。

使用CSS Flex

/*QuickReset*/ * { box-sizing: border-box; margin: 0; }

html {
  height: 100%;
}

body {
  background: black;
  height: 100%;
  position: relative;
  
  display: flex; /* Use flex! */
  padding: 5px; /* Instead of children margin */
  /* gap: 5px; /* Uncomment to add a gap between your child elements! */
}

.one,
.two {
  border: 3px solid green;
  border-radius: 5px;
}

.one { width: 10%; background: red;  }
.two { width: 90%; background: blue; }
<div class="one">
</div>
<div class="two">
</div>

box-sizing: border-box 在元素的总宽度或高度中包含 handling/including 边距,仅包含填充和边框。因此,您必须从宽度或高度值中减去边距值。

在您的情况下,您应该在所有 heightwidth 设置上使用 calc 值,其中有边距。 IE。如果您有 5 像素的边距(= 在所有边上),请在您想要 100% 宽度或高度的地方使用例如 calc(100% - 10px)。与其他百分比值类似 - 请参阅下面的改编代码:

* {
  box-sizing: border-box;
  margin: 0;
}

html {
  width: 100%;
  height: 100%;
}

body {
  background: black;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.one {
  background: red;
  position: absolute;
  width: calc(10% - 10px);
  height: calc(100% - 10px);
  left: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}

.two {
  background: blue;
  position: absolute;
  width: calc(90% - 10px);
  height: calc(10% - 10px);
  right: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}
<div class="one">
</div>
<div class="two">
</div>

.two 的宽度上使用 css 计算函数从 90% 宽度中减去 10px(2x5px 边距),似乎给出了合理的边距。

width: calc(90% - 10px);

我不确定为什么 .one.two 之间没有可见的 10px (2x5px) 边距。

https://developer.mozilla.org/en-US/docs/Web/CSS/calc

* {
  box-sizing: border-box;
  margin: 0;
}

html {
  width: 100%;
  height: 100%;
}

body {
  background: black;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.one {
  background: red;
  position: absolute;
  width: 10%;
  height: 100%;
  left: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}

.two {
  background: blue;
  position: absolute;
  width: calc(90% - 10px);
  height: 100%;
  right: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}
<div class="one">
</div>
<div class="two">
</div>