如何将背景图像添加到空锚标记而不将我的文本显示在图像上?

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

我正在尝试将背景图像放在空锚标记上,并在该图像下方 20px 处显示文本。它位于弹性盒内,因此当我调整屏幕大小时它会做出响应。图像和文本都会出现,但当我希望文本位于图像下方 20 像素时,文本显示在图像顶部。有人有什么建议吗?

我当前的 HTML:

 <section id="store">
      <div class="container flex wrap">
        <div class="splitpage" id="pants">
          <a href="#" aria-label="photo of our various types of pants"></a>
          <h2>Our pants</h2>
          <p>Description of pants here</p>
        </div>

        <div class="splitpage" id="shirts">
          <a href="#" aria-label="photo of our various shirts"></a>
          <h2>Our shirts</h2>
          <p>Description pf shirts here</p>
        </div>
    </section>

我当前的CSS:

#store {overflow: auto; padding: 40px 0;}
.splitpage {width: 50%; margin: 0; text-align: center;}
#store p {padding-top: 20px;}
#pants {background: url(layout1-assets/pants.webp); background-size: cover;}
#shirts {background: url(layout1-assets/shirts.webp); background-size: cover; text-align:   center;}
.container {width: 1040px; margin: 0 auto;}
.flex {display: flex; justify-content: space-between;}
.wrap {flex-wrap: wrap;}
html css flexbox background-image anchor
1个回答
0
投票

由于包含背景图像的 div 是文本的容器,因此它出现在自己的内容之上似乎不自然。

一个简单的解决方法是将容器设置为

position: relative
,创建一个设置
overlay
position: absolute; top: 0; width: 100%; height: 100%;
类。它具有使其目标与其容器大小相同的效果。

然后在标题/文本内容之后使用此

overlay
类将您的图像添加为 div 的背景。就会有自然放在上面的效果

在这里,我用红色和蓝色背景替换了您的图像,并给了它一个

.9
不透明度值,以便您仍然可以看到一点文本并确认它位于“图像”后面

#store {overflow: auto; padding: 40px 0;}
.splitpage {width: 50%; margin: 0; text-align: center; position: relative}
#store p {padding-top: 20px;}
.overlay {position: absolute; top: 0; width: 100%; height: 100%; opacity: 0.9}
#pants {background: red; background-size: cover; }
#shirts {background: blue; background-size: cover; text-align:   center;}
.container {width: 1040px; margin: 0 auto;}
.flex {display: flex; justify-content: space-between;}
.wrap {flex-wrap: wrap;}
<section id="store">
      <div class="container flex wrap">
        <div class="splitpage">
          <a href="#" aria-label="photo of our various types of pants"></a>
          <h2>Our pants</h2>
          <p>Description of pants here</p>
          <div id="pants" class="overlay"></div>
        </div>

        <div class="splitpage">
          <a href="#" aria-label="photo of our various shirts"></a>
          <h2>Our shirts</h2>
          <p>Description pf shirts here</p>
          <div id="shirts"  class="overlay"></div>
        </div>
    </section>

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