有固定孩子的溢出父容器是否可能?

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

我有一个自动高度的父级(例如我为测试pupose添加了300px的高度)和位置为fixed的子元素。即使孩子有固定的位置,只要孩子可以伸展父母elem吗?

<div class="parent">
  <div class="fixed"></div>
</div>

.fixed {
  position: fixed;
  height: 750px;
  width: 100%;
  background: red;
  opacity: 0.5;
  margin: auto;
}

.parent {
  height: 300px;
  background: yellow;
 }

这里的例子是https://jsfiddle.net/hz0wgx1w/

html css css3 css-position fixed
1个回答
0
投票

我想不出用CSS单独做这个的方法,但是这里有一个使用jQuery来更新CSS的示例,以便父级的高度和宽度与孩子的匹配:

https://jsfiddle.net/hz0wgx1w/13/

请记住,在修复子项时,它不会与父项同步滚动,因此这仅适用于设置其初始大小以匹配。滚动时,它无法确保其位置将继续匹配。

这也没有考虑响应性,因此在页面加载后对子项宽度的任何更改都不会导致父级更新,尽管这也可以使用jQuery轻松完成,具体取决于您的目标。

我保留了你的HTML,但如果你计划在其他元素上重用这些类,那么使用不同的ID而不是类会更安全。

$(".parent").css("height", $(".fixed").css("height"));
$(".parent").css("width", $(".fixed").css("width"));
.fixed {
  position: fixed;
  height: 750px;
  width: 100%;
  background: red;
  opacity: 0.5;
  margin: auto;
}

.parent {
  height: 300px;
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="fixed"></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.