% 这个 <div> 所占部分的宽度

% width of what part does this <div> take

所以可能有更简单的方法来解释这个问题,但我是这样知道的:

这基本上是一个下拉菜单中的简单下拉菜单。我知道这个下拉菜单是如何工作的,但这里真正的问题是宽度 .

        <div id="nav2">
            Categories
            <div id="dropcontents">
                <div id="sub-nav">
                    Mobile
                    <div id="sub-dropcontents">
                        <a href="#">Hardware</a>
                        <a href="#">Software</a>
                    </div>
                </div>
                <a href="#">Windows</a>
                <a href="#">News</a>
                <a href="#">Articles</a>
            </div>
        </div>

现在的问题是,如果我将 50% 的宽度分配给 "dropcontents",那么它会占用整个网站宽度的一半。所以它不应该占用 "nav2" 的 50%,因为它在 div 里面吗?我不想在这里使用像素。我注意到 "sub-dropcontents" 占 "dropcontents" 宽度的 50%,我认为这是正确的。

这是图示:

它(任何元素)采用其父元素的百分比宽度。

注意 nav2 是块元素,它将占用其父元素的整个宽度(在本例中为正文)

查看此片段

#nav2{
    border:solid red;

    }
    #dropcontents{
      border:solid;
      width:50%;
    }
<div id="nav2">
  Categories
  <div id="dropcontents">
    <div id="sub-nav">
      Mobile
      <div id="sub-dropcontents">
        <a href="#">Hardware</a>
        <a href="#">Software</a>
      </div>
    </div>
    <a href="#">Windows</a>
    <a href="#">News</a>
    <a href="#">Articles</a>
  </div>
</div>

如果将 nav 的宽度设置为其父宽度的 50%,您会注意到 dropContents div 将调整为 nav2[=17 的 50% =]

请参阅下面的代码段

#nav2 {
  border: solid red;
  width: 50%
}
#dropcontents {
  border: solid;
  width: 50%;
}
<div id="nav2">
  Categories
  <div id="dropcontents">
    <div id="sub-nav">
      Mobile
      <div id="sub-dropcontents">
        <a href="#">Hardware</a>
        <a href="#">Software</a>
      </div>
    </div>
    <a href="#">Windows</a>
    <a href="#">News</a>
    <a href="#">Articles</a>
  </div>
</div>

问题是 position 值:

如果parent和children没有定位,children的50%宽度就是parent

的50%宽度

如果children是position:absolute;宽度的50%,表示定位的第一个parent的50%;如果没有 parent 它将引用整个文档的百分比。

要解决这个问题,只需将 position:something; 放在百分比必须引用的 div 中。

要获得更好的解释,请参阅此 DEMO

.parent {
  width: 500px;
  height: 200px;
  background-color: red;
  margin-bottom:10px;
}

.child {
  width: 50%;
  height: 200px;
  background-color: blue;
}

.absolute {
  position:absolute;
}
.relative {
  position:relative;
}
Parent-> not positioned and Child -> not positioned
<div class="parent">
  <div class="child">
  </div>
</div>
Parent-> not positioned and Child -> absolute
<div class="parent">
  <div class="child absolute">
  </div>
</div>
Parent-> relative and Child -> absolute
<div class="parent relative">
  <div class="child absolute">
  </div>
</div>
Parent-> absolute and Child -> absolute
<div class="parent absolute">
  <div class="child absolute">
  </div>
</div>