【问题标题】:How to achieve 100% parent width for a fixed child? [duplicate]如何为固定的孩子实现 100% 的父宽度? [复制]
【发布时间】:2018-12-31 07:56:07
【问题描述】:

运行下面的 sn-p 以查看我想要实现的目标。

主要问题是:没有 JavaScript 是否有可能实现这一目标?

.container {
  display: flex;
  width: 400px;
  height: 2000px;
  background-color: #aaa;
}

.left {
  width: 150px;
  background-color: lightgreen;
}

.right {
  width: 100%;
  background-color: lightcoral;
}

.fixed {
  position: fixed;
  height: 100px;
  width: 100%;
  background-color: skyblue;
}
<div class="container">
  <div class="left">
    My width can change anytime.
  </div>
  <div class="right">
    <div class="fixed">
      I'm fixed. Scroll the page to verify.<br /> I want to be the same width as my red parent.<br /> Any tips?
    </div>
  </div>
</div>

【问题讨论】:

  • 我的回答很快,而且只适用于某些情况......顺便说一句,为什么不考虑粘性位置?您将获得与固定效果几乎相同的效果
  • 这里是一个例子:jsfiddle.net/ywavjqpd
  • 一定要关注欺骗链接的链接帖子,因为在某些情况下可以让它发挥作用。

标签: css flexbox css-position


【解决方案1】:

您实际上可以根据 flex 项的宽度计算它需要具有的宽度。

左侧项目的宽度为 150 像素,右侧项目的宽度为 100%(解析为 400 像素)。总计 550 像素,并被压缩到 400 像素的 flex 容器中,因此正确项目的实际使用宽度是 400 像素 *(400/550)。
(当然,这是在没有任何扭曲因素的情况下进行的,例如 flex-grow,这会使整个计算变得更加复杂!)

.container {
  display: flex;
  width: 400px;
  height: 2000px;
  background-color: #aaa;
}

.left {
  width: 150px;
  background-color: lightgreen;
}

.right {
  width: 100%;
  background-color: lightcoral;
  position:relative;
  
}

.fixed {
  position: fixed;
  height: 100px;
  background-color: skyblue;
  width:calc(400px * (400 / (400 + 150)));
}
<div class="container">
  <div class="left">
    My width can change anytime.
  </div>
  <div class="right">
    <div class="fixed">
      I'm fixed. Scroll the page to verify.<br > I want to be the same width as my red parent.<br > Any tips?
    </div>
  </div>
</div>

【讨论】:

  • 我可能会添加一些 CSS 变量,因为据我所知,绿色的宽度可以随时更改,因此最好将它们与相同的变量联系起来
  • 是的,但我不想让示例变得比演示该技术所需的复杂。我不能使用 100% 而不是 400px,这已经够糟糕了。
  • 是的,就像@TemaniAfif 指出的那样,绿色区域的宽度是未知的,并且可以随时更改,所以硬编码它并没有真正起作用。
  • @MishaMoroshko 很抱歉。我有点希望你的意思是宽度是未知的,因为它们是灵活的,并且能够计算结果会有所帮助。我也要删除我的答案吗?
猜你喜欢
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
  • 2017-10-26
  • 2017-06-03
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多