How to fit sizes of background and foreground laye

2019-09-19 09:57发布

问题:

In my web app, I have a background and an overlay layer, both can grow, and if one of them grows, the other should grow to the same size. In other words: I have a stack of HTML elements, and their sizes should be in sync, following the biggest element.

Is there a way to do this with a plain flex layout? (without float and transform hacks)

Here's some pseudo code to outline my problem:

<container>
   <background>has min-height of container height. Can grow (and cause scrollbars) if dynamic content takes more height</background>
   <foreground>some overlay that should cover the background completely (following the size of the 'background' element, not the size of the 'container' element.)</foreground>
</container>

回答1:

I came up with the following solution:

  • use flex items with each 100% size of the flex container,
  • set margin-left to -100% for each of the items except for the first one.

/* demo setup */

* {
  margin: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  align-items: center;
  font-size: 16pt;
}

section {
  flex-basis: 0;
  border: 3px dashed blue;
}

.background {
  background-color: beige;
}

.overlay1 {
  background: linear-gradient(180deg, rgba(255, 0, 0, 0.5) 0%, rgba(255, 0, 0, 0) 100%);
  text-align: right;
}

.overlay2 {
  background: linear-gradient(90deg, rgba(0, 255, 0, 0.5) 0%, rgba(0, 255, 0, 0) 100%);
}

/* actual solution */

.flex-stack {
  display: flex;
}

.flex-stack>* {
  flex-grow: 1;
  flex-basis: 0;
  margin-left: -100%;
}

.flex-stack> :first-child {
  margin-left: 0;
}
<section class="flex-stack">
  <p class="background" style="min-height:8em;">
    This is the background layer.
  </p>
  <p class="overlay1"><br> this is some overlay box.
  </p>
  <p class="overlay2"><br><br>
    <textarea style="resize: both;">This is resizable content: drag the lower left corner of the the textarea.
  </textarea><br> this is another overlay box.
  </p>
</section>