sean sean - 4 years ago 159
HTML Question

How to make div's percentage width relative to parent div and not viewport

Here is the HTML I am working with.



<div id="outer" style="min-width: 2000px; min-height: 1000px; background: #3e3e3e;">
<div id="inner" style="left: 1%; top: 45px; width: 50%; height: auto; position: absolute; z-index: 1;">
<div style="background: #efffef; position: absolute; height: 400px; right: 0px; left: 0px;"></div>
</div>
</div>





What I would like to happen is for the inner div to occupy 50% of the space given to its parent div(outer). Instead, is is getting 50% of the space available to the viewport, which means that as the browser/viewport shrinks in size, so does it.

Given that the outer div has
min-width
of
2000px
, I would expect the inner div to be at least
1000px
wide.

Answer Source

Specifying position:relative;or position:absolute; on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

#outer {
  min-width: 2000px; 
  min-height: 1000px; 
  background: #3e3e3e; 
  position:relative
}

#inner {
  left: 1%; 
  top: 45px; 
  width: 50%; 
  height: auto; 
  position: absolute; 
  z-index: 1;
}

#inner-inner {
  background: #efffef;
  position: absolute; 
  height: 400px; 
  right: 0px; 
  left: 0px;
}
<div id="outer">
  <div id="inner">
    <div id="inner-inner"></div>
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download