【问题标题】:How to fit sizes of background and foreground layer using CSS flexbox如何使用 CSS flexbox 调整背景和前景层的大小
【发布时间】:2018-10-07 16:53:29
【问题描述】:

在我的网络应用中,我有一个背景层和一个覆盖层,两者都可以增长,如果其中一个增长,另一个应该增长到相同的大小.换句话说:我有一堆 HTML 元素,它们的大小应该是同步的,跟在最大的元素之后。

有没有办法用普通的 flex 布局来做到这一点? (没有 floattransform 黑客)

这里有一些伪代码来概括我的问题:

<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>

【问题讨论】:

  • 我们需要看到问题,而不仅仅是您提供的解决方案
  • @TemaniAfif 不确定你错过了什么......
  • 一切,你描述了你自己的问题,我们看不到它......没有代码,所以这有什么帮助?我们需要看到这个问题。如果有人有更好的解决方案怎么办?
  • @TemaniAfif 我认为我的回答很能说明问题的结构。如果你找到更好的造型方式,我会非常欢迎。其实我的回答概括了我原来的问题,所以我把它添加到问题中。
  • 实际上我的理解是您在使用自己的应用程序时遇到了问题,您找到了解决方法,但我们不知道您想做什么?目的是什么?问题是什么?这对未来的读者有什么帮助? ...你描述的东西太宽泛了,你提供了一个代码做一些我们不知道的事情。我在背景上看到了一个文本,我们可以很容易地用多个背景来做,所以我看不出这与 flexbox 有什么关系。

标签: html css layout flexbox


【解决方案1】:

我想出了以下解决方案:

  • 使用具有每个 100% 大小的弹性容器的弹性项目,
  • 将除第一个项目之外的每个项目的 margin-left 设置为 -100%

/* 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2018-07-28
    • 2012-01-14
    • 2010-11-17
    • 1970-01-01
    • 2018-12-23
    相关资源
    最近更新 更多