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

后端 未结 2 2012
执念已碎
执念已碎 2020-11-27 15:42

Here is the HTML I am working with.

相关标签:
2条回答
  • 2020-11-27 16:23

    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>

    0 讨论(0)
  • 2020-11-27 16:32

    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.

    0 讨论(0)
提交回复
热议问题