:before
creates a virtual content using CSS, so in the above case, author uses below snippet means
.parent:before{
z-index:-1;
content:'';
position:absolute;
opacity:0.5;
width:400px;
height:200px;
background-image:url('wallpaper324845.jpg');
border:1px solid red;
}
He is creating a virtual element using :before
, which he then positions absolute
, assigns some dimensions, and assigns the background
, to make sure that it stays below the div
content, he uses z-index: -1;
In other words, :before
, :after
are nothing but assume nesting two span
elements inside your div
, but by using pseudo
elements, you don't need to have span
as you can achieve the same thing with the pseudo elements.
Consider you have something like this
<div>
Hello
<span></span>
</div>
div {
position: relative;
}
div span {
position: absolute;
width: 100%;
height: 100%;
background: #f00;
z-index: -1;
left: 0;
top: 0;
}
Can be also achieved using :before
or :after
, markup stays the same but CSS goes like
div {
position: relative;
}
div:after {
content: "";
position: absolute;
width: 100%;
height: 100%;
background: #f00;
z-index: -1;
left: 0;
top: 0;
}
So, it just saves you one empty element in your HTML, but if you look at the above CSS, am using content
property which is ALWAYS associated with :before
or :after
, and yes, it is required, even if you keep it blank.
Also, note that :before
and :after
generated content are inline, so inorder to make height
, width
work, you need to explicitly mention display: block;
or display: inline-block;
if you want to make it block level, but in this particular case, you won't need that as the pseudo element is positioned absolute
div:after {
content: "Hello";
margin-top: 20px; /* This wont work as pseudo is inline by default */
}
So make it block
or inline-block