Html 如何使 div 的百分比宽度相对于父 div 而不是视口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13867717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:22:27  来源:igfitidea点击:

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

htmlcsswidthcss-position

提问by sean

Here is the HTML I am working with.

这是我正在使用的 HTML

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

我想要发生的是内部 div 占据其父 div(外部)空间的 50%。相反,它获得了 50% 的视口可用空间,这意味着随着浏览器/视口的尺寸缩小,它也会缩小。

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

鉴于外div有min-width2000px,我希望内部的div至少1000px宽。

回答by Juan Mendes

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

指定一个非静态位置,例如,position: absolute/relative在节点上意味着它将用作其中绝对定位元素的参考http://jsfiddle.net/E5eEk/1/

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

请参阅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>

回答by William

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.

另请注意,如果您没有向任何 div 添加任何位置属性,您就不会看到这种行为。胡安进一步解释。