此<div>采取的部分的宽度%

时间:2016-10-30 16:11:48

标签: html css html5 width percentage

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

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

        <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>

现在的问题是,如果我给“dropcontents”提供50%的宽度,那么它就像整个网站宽度的一半。所以它不应该占据50%的“nav2”,因为它在那个div里面?而且我不想在这里使用像素。我注意到“sub-dropcontents”占据了50%的“dropcontents”宽度,我认为这是正确的。

这是图形表示: enter image description here

3 个答案:

答案 0 :(得分:1)

问题是position值:

如果未定位父项和子项,则子项的宽度为50%表示父项的宽度为50%

如果孩子是position:absolute;,宽度的50%意味着定位的第一个父母的50%;如果没有任何父母,它会将百分比提交给整个文件。

要解决此问题,只需将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>

答案 1 :(得分:0)

it(any element)获取其父元素的百分比宽度。

答案 2 :(得分:0)

注意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>

如果您将导航的宽度设置为其父宽度的50%,您会注意到dropContents div将调整为nav2的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>