html - 为什么 div 百分比 margin 不正确?

标签 html css

我目前遇到的问题是,我为子 div 使用的百分比相对于父 div 似乎不起作用。

<div id="NavBar">
    <div class="Button"></div>
    <div class="Button"></div>
    <div class="Button"></div>
    <div class="Button"></div>
    <div class="Button"></div>
</div>

#NavBar {
    Height:10vh;
    Width:100%;
    background-color:gray;
    float:left;
    position:relative;

.Button {
    Height:90%;
    Width:10%;
    margin-left:8.5%;
    margin-top:5%;
    background-color:Black;
    float:left;

https://jsfiddle.net/7duea0ou/

父 div 的 5% 肯定不是它的整个高度,我不确定是什么导致了这个问题。

如何使边距仅为父 div 的 5%?

最佳答案

边距中使用的 % 值是指父级 width不是 height 即使对于 margin-top 和 margin-bottom 也是如此。如您所见here :

The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

因此,您可以考虑进行一些计算并使用变量,而不是使用 %。

这是一个例子:

:root {
  --main-height: 10vh; /*we define the height of the navbar*/
}

#NavBar {
  height: var(--main-height);
  Width: 100%;
  background-color: gray;
  float: left;
  position: relative;
}

.Button {
  height: 90%;
  width: 10%;
  margin-left: 8.5%;
  margin-top: calc((var(--main-height) * 5) / 100); /* we take 5% of the height*/
  background-color: Black;
  float: left;
}
<div id="NavBar">
  <div class="Button"></div>
  <div class="Button"></div>
  <div class="Button"></div>
  <div class="Button"></div>
  <div class="Button"></div>
</div>

顺便说一下,您的代码可以使用 flex 进行简化并且无需设置边距值:

#NavBar {
  height: 10vh;
  background-color: gray;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}

.Button {
  height: 90%;
  flex-basis: 10%;
  background-color: Black;
}
<div id="NavBar">
  <div class="Button"></div>
  <div class="Button"></div>
  <div class="Button"></div>
  <div class="Button"></div>
  <div class="Button"></div>
</div>


这是一个类似的问题,您可以在其中找到更多方法:

How to set the margin or padding as percentage of height of parent container?

关于html - 为什么 div 百分比 margin 不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491347/

相关文章:

html - 奇怪的边框位置

jquery - ColorPicker 绑定(bind)颜色

html - 为什么 flex 元素不缩小过去的内容大小?

javascript - 我无法使用 Javascript 显示图像

javascript - 在 DIV 中显示光标

html - 如何设置段落的字符数限制?

javascript - Jquery 按钮标签选项不适用于输入类型复选框

jquery - 当文本溢出时使 JQuery Marquee

html - 如何去除焦点上的 iframe 高亮边框?

html - CSS 行间隙和列间隙一样吗?