我正在尝试在 div 的右侧放置一个背景图像,它没有覆盖整个 div。
现在是这样的(div1 是背景色):
<div id="div1">
<div id="image"></div>
Text
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
.div1 {
background: #324458;
color: #FFF;
font-size: 0.9em;
font-weight: bold;
padding: 10px;
width: 100%;
position: relative;
border-radius:4px;
height:40px;
clear:both;
overflow: hidden;
}
.image {
background: url("url here");
background-position: center center;
background-size: cover;
opacity: 0.3;
height: 39px;
margin: -10px;
width: 300px;
position:absolute;
right: 10px;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
z-index: 0;
}
Run Code Online (Sandbox Code Playgroud)
但是是否可以在其中显示图像而不将其作为 div1 中的 div?喜欢使用:after,:before还是其他什么?我只希望 divimage显示在 div1 的右侧并且是 X 宽度。
要在诸如 ::after 和 ::before 之类的伪元素上显示背景图像,您应该将content: '';它们包含在内。
我已经修复(你试图用类选择器定位 ID)并在这个 fiddle上添加了提到的背景图像。但它是这样的:
.div1 {
background: #324458;
color: #FFF;
font-size: 0.9em;
font-weight: bold;
padding: 10px;
width: 100%;
position: relative;
border-radius: 4px;
height: 40px;
clear: both;
overflow: hidden;
}
.div1::after {
content: '';
background: url("https://unsplash.it/200/300");
background-position: center center;
background-size: cover;
opacity: 0.3;
height: 39px;
margin: -10px;
width: 300px;
position: absolute;
right: 10px;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
z-index: 0;
}Run Code Online (Sandbox Code Playgroud)
<div class="div1">
Text
</div>Run Code Online (Sandbox Code Playgroud)