The ::before and ::after Pseudo-element in CSS

CSSWeb DevelopmentFront End Technology

The CSS ::before and CSS ::after Pseudo-element are used to insert some content before and after the element respectively.

Example

Let’s see an example for CSS ::before and CSS ::after Pseudo-elements −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div:nth-of-type(1) p:nth-child(2)::after {
   content: " BUZZINGA!";
   background: orange;
   padding: 5px;
}
div:nth-of-type(2) p:nth-child(2)::before {
   content: "Harry:";
   background-color: lightblue;
   font-weight: bold;
   padding: 5px;
}
</style>
</head>
<body>
<div>
<p>Nobody: </p>
<p>Sheldon Cooper:</p>
</div><hr><div>
<p><q>Death Eaters arrive</q></p>
<p><q>Expecto Patronum!</q></p>
</div>
</body>
</html>

Output

This will produce the following output −

Example

Let’s see another example for CSS ::before and CSS ::after Pseudo-elements −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>Center Alignment using CSS Margin</title>
<style>
#yinyangSymbol {
   width: 100px;
   height: 50px;
   background: #fff;
   border-color: #000;
   border-style: solid;
   border-width: 2px 2px 50px 2px;
   border-radius: 100%;
   position: relative;
}
#yinyangSymbol::before {
   content: "";
   position: absolute;
   top: 50%;
   left: 0;
   background: #fff;
   border: 18px solid #000;
   border-radius: 100%;
   width: 14px;
   height: 14px;
}
#yinyangSymbol::after {
   content: "";
   position: absolute;
   top: 50%;
   left: 50%;
   background: #000;
   border: 18px solid #fff;
   border-radius:100%;
   width: 14px;
   height: 14px;
}
div{
   width: 50%;
   margin: 10px auto;
   border:4px solid black;
}
#text {
   border: 4px solid black;
   background-color: grey;
   color: white;
   text-align: center;
}
</style>
</head>
<body>
<div id="main">
<div>
<div id="yinyangSymbol"></div>
</div>
<div id="text">Be Centered & Balanced</div>
</div>
</body>
</html>

Output

This will produce the following output −

raja
Published on 07-Jan-2020 11:21:22
Advertisements