首页 > 解决方案 > 元素之间的背景放置

问题描述

我有疑问是否有可能在我的下一个 div 中也可以看到第二个 div 的背景。

<div style="max-width:100%;width:100%;">
...
</div>
<div style="max-width:100%;width:100%; background:url('someimage.png')">
...
</div>
<div style="max-width:1200px; width:100%">
...
</div>

或者我必须使用图像并将其绝对定位:

<div style="max-width:100%;width:100%;">
...
</div>
<div style="max-width:100%;width:100%;position:relative;z-index:2">
...
</div>
<img src="someimage.png" style="position:absolute;width:100%;height:300px;z-index:1" />
<div style="max-width:1200px; width:100%;position:relative;z-index:2;">
...
</div>

但在图像的情况下,我将无法相对于第二个 div 正确定位它。

除非有其他方法?

需要这样的东西: 在此处输入图像描述

标签: css

解决方案


如果你想要水印之类的东西

  1. 您需要position在 div 和 img 中定义。
  2. 图片需要position: absolute

您需要在 div 和 img 中定义位置。Img 需要位置:绝对。但是如果你想设置背景,更好的解决方案是background-image 属性

或者像一张卡片

<style>
.card {
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  transition: 0.3s;
  width: 40%;
}

.card > img {
  padding-top: 16px;
  display: block;
  margin: 0 auto;
}

.container {
  padding: 2px 16px;
}
</style>
</head>
<body>

<h2>Card</h2>

<div class="card">
  <img src="img_avatar.png" alt="Avatar" style="width:30%">
  <div class="container">
    <h4><b>John Doe</b></h4> 
    <p>Architect & Engineer</p> 
  </div>
</div>

卡片

或混合解决方案

<style>
.card {
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  transition: 0.3s;
  width: 40%;
  height: 300px;
  background-image: url("img_avatar.png");
}

.container {
  padding: 2px 16px;
}
</style>
</head>
<body>

<div class="card">
  <div class="container">
    <h4><b>John Doe</b></h4> 
    <p>Architect & Engineer</p> 
  </div>
</div>

背景图片


推荐阅读