【问题标题】:Two background images, one with a percentage size and the other one cover what's left?两张背景图片,一张有百分比大小,另一张覆盖剩下的内容?
【发布时间】:2019-11-26 22:52:17
【问题描述】:
我有一个 div,我希望 div 的一半被渐变覆盖,另一半是普通图像,但效果与background-size:cover; 相同,并填充右侧的剩余空间的梯度。这可能吗?
div {
width:100%;
height:400px;
background-image:url(http://placehold.it/100x100);
background-size: 50% cover;
background-position: 100% center;
background-repeat:no-repeat;
}
div:before {
content:"";
display:block;
width:50%;
height:100%;
background-image: linear-gradient(red, yellow);
}
<div></div>
不幸的是,这似乎不起作用。我可以使用background-size: 50% auto;,但这并不能完全满足我的需求。我意识到我可以把它分成两个 div,但我只是想看看是否可以用一个来做到这一点。
【问题讨论】:
标签:
css
background-image
background-position
【解决方案1】:
使用多个背景和一些填充,背景来源技巧。这个想法是将填充定义为宽度的一半,并将图像放在内容框上,内容框将是另一半。
您必须使用vw 单位,但有一个小缺点,因为它考虑了滚动的宽度。如果 div 不是全宽 div,这也可能是一个问题。
.box {
padding-left:50vw;
height:300px;
background:
linear-gradient(red, yellow) left/50vw 100%,
url(http://placehold.it/400x400) center/cover content-box;
background-repeat:no-repeat;
}
body {
margin:0;
}
<div class="box"></div>
或者干脆同时使用两个伪元素:
.box {
height:300px;
position:relative;
}
div::before,
div::after {
content:"";
position:absolute;
top:0;
bottom:0;
width:50%;
}
div::before {
left:0;
background:linear-gradient(red, yellow);
}
div::after {
right:0;
background:url(http://placehold.it/400x400) center/cover;
}
body {
margin:0;
}
<div class="box"></div>