CSS 大小嵌套 DIV 基于父级父 DIV 大小

问题描述 投票:0回答:1

假设我有这个 HTML

<div id="outer">
  <div id="inner">
    <div id="nested">
    </div>
  </div>
</div>

哪里

  • 所有 DIV 都是响应式的,因为 #outer 的宽度是窗口宽度的百分比
  • #inner“总是”小于#outer

使用CSS,有没有办法设置#nested的宽度,使其成为#outer宽度的百分比?

html css parent percentage
1个回答
0
投票

您可以使用

position: relative
position: absolute

来实现

这两个属性是齐头并进的,因为

absolute
元素相对于其最近的父/祖先进行定位。如果没有找到,它会上升到
body
标签。通过在
position: relative
上设置
outer
,可以使其成为最近的祖先,因此
nested
的宽度会相应调整。

#outer {
  height: 10rem;
  width: 80vw; /* 80% of the screen width */
  background: red;
  position: relative;
}

#inner {
  height: 10rem;
  width: 80%;
  background: gray;
}

#nested {
  height: 10rem;
  width: 50%;
  background: black;
  position: absolute;
}
<div id="outer">
  <div id="inner">
    <div id="nested">
    </div>
  </div>
</div>

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