P. Nick P. Nick - 1 month ago 6
CSS Question

Image in div with :after or :before?

I'm trying to have a background image to the right of a div, which isn't covering the whole div.

Right now it's like this (div1 is background-color):

<div id="div1">
<div id="image"></div>
Text
</div>


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;
}


But is it possible to have the image shown in it without having it as a div inside div1? Like using
:after
,
:before
or something else? I only want the div
image
to show to the right of div1 and be X width.

Answer

For an background image to show on pseudo-elements like ::after and ::before you should include content: ''; on them.

I've fixed (you were trying to target ids with class selectors) and added the mentioned background image on on this fiddle. But it goes like this:

HTML :

<div class="div1">
    Text
</div>

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;
}

.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;
}