为什么我看不到红色 div 框?

Why can't I see a red div box?

body {
  background-color: teal;
}

.gridBox {
  position: relative;
  display: block;
  height: 20%;
  width: 20%;
  background-color: red;
}
<div class="gridBox">
  <div id="grid"> </div>
</div>

我的 .gridBox div 有什么问题?当我将它设置为像素时,我可以看到它。但是百分比不起作用。因为是body的子元素,.gridBox不是继承了浏览器的宽高window吗?嗯?

您需要添加 div 的 parents 的 widthheight。那是因为此元素从正文中获取 heightwidth,然后是 html - 未设置。

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

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

body {
  background-color: teal;
}

.gridBox {
  display: block;
  height: 20%;
  width: 20%;
  background-color: red;
}
<div class="gridBox">
  <div id="grid"> </div>
</div>

为正文添加 css width/height 和 html

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

您可以使用 vhvw 而不是 %

vh 是视口高度的百分比。 vw 是视口宽度的百分比。

body {
  background-color: teal;
}

.gridBox {
  display: block;
  height: 20vh;
  width: 20vw;
  background-color: red;
}
<div class="gridBox">
  <div id="grid"> </div>
</div>

另一方面,您可以使用 %,但如果您这样做,则需要将 htmlbody 设置为 height: 100%; width: 100%;,然后设置 margin: 0;删除导致滚动条的额外 space。

body, html {
  background-color: teal;
  height: 100%;
  width: 100%;
  margin: 0;
}

.gridBox {
  display: block;
  height: 20%;
  width: 20%;
  background-color: red;
}
<div class="gridBox">
  <div id="grid"> </div>
</div>

gridBox 从 body 获取高度,在本例中为 null。所以试试

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

或者只给出 gridBox 的像素高度。

.gridbox {
   height : 100px;
}
  1. The issue here is that you haven't set a width and height of body/html, so therefore when give width: 20%; width: 20%; it does not show. (20% of what?)

添加 body/html

的宽度和高度

body,html {
  background-color: teal;
  width: 100%;
  height: 100%;
}

.gridBox {
  position: relative;
  display: block;
  height: 20%;
  width: 20%;
  background-color: red;
}
<div class="gridBox">
  <div id="grid"> </div>
</div>

这是有内容的

如果您添加内容,它将显示。

 body {
      background-color: teal;
    }

    .gridBox {
      position: relative;
      display: block;
      height: 20%;
      width: 20%;
      background-color: red;
    }
    <div class="gridBox">
      <div id="grid">aaa </div>
    </div>

  1. You haven't given vh or vw to width & height to the div.

 body {
      background-color: teal;
    }

    .gridBox {
      position: relative;
      display: block;
      height: 20vh;
      width: 20vw;
      background-color: red;

    }
    <div class="gridBox">
      <div id="grid"> </div>
    </div>

解法:

使用 vh vw 为 div 指定宽度和高度,或将内容添加到红色框或设置 body/html 宽度和高度。

您可以删除 position: relative; 它会完成工作(目前)

  .gridBox {
  display: block;
  height: 20%;
  width: 20%;
  background-color: red;
}