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

问题描述 投票:49回答:2

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>

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

鉴于外部div有min-width2000px,我预计内部div至少是1000px宽。

html css width css-position
2个回答
55
投票

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

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

我们可以更改定位上下文 - 绝对定位元素相对于哪个元素。这是通过在元素的一个祖先上设置定位来完成的。

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

10
投票

在父元素上使用position:relative。

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

© www.soinside.com 2019 - 2024. All rights reserved.