使用flexbox,如何覆盖图像并展开以填充父容器

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

在以下html中,我希望txt-box div在容器中居中,覆盖图像,然后展开以填充容器。它的所有边均应具有相等宽度的边距,以使图像的一部分显示为粗边框。

显示的html对于我想要的内容是可以通过的,但随着浏览器窗口大小的调整,垂直和水平边距总是略有不同。

[我觉得这里有一个黑客,而且我没有正确使用flex-grow。我知道flex-grow可以使txt-box div扩展,因为它是唯一具有增长值的元素。如果我能解决这个问题,我应该可以简单地在txt-box上设置一个边距,它应该可以工作。

我对flex-grow不了解什么?

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  border: solid 2px red;
  position: relative;
}

.container img {
  width: 100%;
  flex-grow: 0;
  flex-shrink: 0;
}

.txt-box {
  background-color: white;
  display: flex;
  padding: 5px;
  border: solid 2px blue;
  flex-grow: 1;
  position: absolute;
  width: 90%;
  height: 80%;
}
<div class="container">
  <img src="blocks.png" />
  <div class="txt-box">
    hello world
  </div>
</div>
html css flexbox
1个回答
0
投票

我对flex-grow不了解什么?

Flex属性在flex容器的绝对定位子元素上不起作用。

§ 4.1. Absolutely-Positioned Flex Children

由于流出,是flex的绝对定位子元素容器不参与弹性布局。

因此,flex-grow: 1上的txt-box没有执行任何操作。它只是被忽略。

考虑到您只希望将图像放置在背景中,并且文本框有更多要求,请考虑绝对放置图像,并使文本框保持正常流动。

然后为文本框提供完整的宽度和高度,并在主容器上使用相同的填充,以在整个屏幕尺寸上保持统一的“边距”。

这里是一个演示,具有一些额外的功能来帮助说明所涉及的概念。

 body {
   height: 100vh;   
   display: flex;
   margin: 0;
   padding: 10px;
 }
 
 .container {
   flex-grow: 1;
   display: flex;
   align-items: center;
   justify-content: center;
   padding: 20px;
   position: relative;
   border: solid 2px red;
 }
 
 img {
   position: absolute;
   height: 100%;
   width: 100%;
   object-fit: contain; /* also try 'cover' for demo */
 }

 .txt-box {
   z-index: 1;
   width: 100%;
   height: 100%;
   border: solid 2px blue;
   background-color: rgba(192,192,192,0.5);
 }
  
 * {
   box-sizing: border-box;
 }
<div class="container">
  <img src="http://i.imgur.com/60PVLis.png">
  <div class="txt-box">hello world</div>
</div>

jsFiddle demo

© www.soinside.com 2019 - 2024. All rights reserved.