CSS响应背景图像为全尺寸图像

CSS responsive background image as full-sized image

本文关键字:图像 全尺寸 背景 响应 CSS      更新时间:2023-09-26

我试图将两个图像叠加在一起,我发现最简单的方法是将一个设置为header标签的背景图像,然后将另一个设置在header标签内部。

然而,我想设置的背景图像是需要完整显示的横幅,作为背景图像,它周围的标签大小下降到只适合它上面的第二个图像的大小。

我想保持横幅/背景图像的大小响应,所以我不能只设置特定的高度和宽度。

如何使背景图像充当横幅?(同时仍然将我的第二张图像分层在顶部?)

HTML

<header>
    <img src="topImage.jpg" />
</header>

CSS

header{
    background-image: url('bannerImage.jpg');
    background-repeat: no-repeat;
    background-position: top center;
    background-size: 100% auto;
}
/*This image is smaller than the background banner image*/
header img{
    display: block;
    max-width: 20%;
    height: auto;
}

我正在寻求一个CSS解决方案,但如果适用的话,也可以对JavaScript开放。请不要Jquery。

编辑:对不起,当我说div时,我只是指我应用了样式的标签。更新了问题以反映这一点。

您可以在页面正文中使用一个图像,并对其应用Z索引(横幅图像)。

//Banner image
.imgOne
{
     position: absolute  !important;
     left: 0px;
     top: 0px;
     z-index: -1 !important;
     width:100%;
     height:100%;
}
//Second overlaying image
.imgTwo
{
     position: relative;
     width:30% !important;
     float :left; //Optional; you could specify left and top for position
     height:30% !important;
}

如果你在第二个图像上使用float,你可以看到结果。如果你不想让其他元素在第二张图像周围浮动,你可以对这些元素使用clear属性,如下所示。

p {
    border: 1px solid red;
    clear: left;
}

为之奋斗:https://jsfiddle.net/e1hysrce/

Lmk,如果它对你有效,或者如果你找到了更好的分享。