
如何在小程序中使用相对定位压住图片
在小程序中,使用 margin-top:-130rpx 将文字放置在图片上方,但灰色背景不可见。如何解决?
为了压住图片并显示灰色背景,可以使用相对定位和 z-index。以下是修改后的代码:
.index{
width: 100%;
height: 100vh;
}
.title{
width: 100%;
height: 520rpx;
background-color: #ccc;
border-top-left-radius: 30rpx;
border-top-right-radius: 30rpx;
overflow: hidden;
position: relative;
z-index: 2;
top: -130rpx;
border-radius: 30rpx;
}- 相对定位 .title: 为 .title 元素设置 position: relative;。这会将其相对于其容器进行定位。
- z-index: 将 .title 的 z-index 设置为 2。这将确保它位于其容器中的其他元素之上。
- top: 将 margin-top 改为 top:-130rpx;。使用 top 属性可以从 .title 的顶部偏移 130 个像素。
通过这些更改,.title 元素将相对于其容器进行定位,并且由于 z-index 较高,它将位于图片之上。灰色背景现在将可见,文字将位于图片上方。










