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

时间秒杀一切 提交于 2019-11-26 09:29:45

问题


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.


回答1:


Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

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



回答2:


Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.



来源:https://stackoverflow.com/questions/13867717/how-to-make-divs-percentage-width-relative-to-parent-div-and-not-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!