Manu Karki Manu Karki - 1 month ago 5
CSS Question

% width of what part does this <div> take

So there might be an easier way to explain this problem but this is how I know:

This basically is a simple dropdown menu inside a dropdown menu. I know how this dropdown works but the real problem here is width of .

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


Now the question is if I give 50% width to "dropcontents" then it takes like the half the whole website width. SO isn't it supposed to take 50% of "nav2" as it is inside that div? And I don't want to use pixel here. And I noted that "sub-dropcontents" take 50% width of "dropcontents" which I assume is correct.

Here's the pictorial representation:
enter image description here

Answer

The problem is the position value:

If the parent and the children are not positioned, 50% width for the children means 50% width of the parent

If the children is position:absolute; 50% of width means 50% of the first parent that is positioned; if there is not any parent it'll refer the percentage to the whole document.

To fix that just put position:something; in the div that the percentage must refer to.

For a better explanation see this 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>