我有一个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,但是我只想看看是否可以用一个div。
[使用多个背景和一些填充背景起源的技巧。想法是将填充定义为宽度的一半,然后将图像放在内容框(另一半)上。
您必须使用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>