1

Run the snippet below to see what I'm trying to achieve.

The main question is: Is that possible to achieve this without 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>
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

0

You can actually calculate the width it needs to have, based on the widths of the flex items.

The left item is given a width of 150px and the right item 100% (which resolves to 400px). This totals 550px, and that gets squeezed into the 400px flex container, so the actually used width for the right item is 400px *(400/550).
(Of course this is in the absense of any distorting factors such as flex-grow, which would make the whole calculation a lot more complex!)

.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>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
  • 1
    I would probably add some CSS variables because as I can read, the width of the green can change anytime so better link them with the same variable – Temani Afif Jul 23 '18 at 20:14
  • Yes, but I didn't want to make the example more complicated than necessary to demonstrate the technique. It's bad enough that I wasn't able to use 100% instead of 400px. – Mr Lister Jul 23 '18 at 20:22
  • Yeah, like @TemaniAfif pointed out, the width of the green area is unknown and can change anytime, so hardcoding it doesn't really work. – Misha Moroshko Jul 23 '18 at 22:51
  • @MishaMoroshko Sorry about that. I was kinda hoping that you meant the widths were unknown because they were flexible, and that being able to calculate the outcome would help. Shall I delete my answer too? – Mr Lister Jul 24 '18 at 07:10