The content property in CSS is used with the ::before and ::after pseudo-elements to insert generated content into an element. This property is particularly useful for adding decorative content or symbols without modifying the HTML structure.
The content property can be used to insert text, images, or symbols before or after an element. Here are some basic examples:
Example: Adding Text
p::before {
content: "Before - ";
color: blue;
}
p::after {
content: " - After";
color: green;
}
In this example, text is added before and after a paragraph using the ::before and ::after pseudo-elements.
The content property can also be used to add symbols or icons. This can be done using Unicode characters or icon fonts.
Example: Adding Symbols
ul li::before {
content: "↑"; /* Unicode checkmark character */
color: green;
margin-right: 10px;
}
ul li::after {
content: "♥"; /* Unicode cross mark character */
color: red;
margin-left: 10px;
}
In this example, symbols are added before and after list items using the content property with Unicode characters.
You can use the content property to insert images as well. This is useful for adding decorative images without changing the HTML.
Example: Inserting Images
.element::before {
content: url('/images/common/cute_100x100_cat.png');
display: inline-block;
margin-right: 10px;
}
.element::after {
content: url('/images/common/cutedog_100x100.png');
display: inline-block;
margin-left: 10px;
}
In this example, images are inserted before and after elements using the url() function with the content property.
The content property can also be used conditionally to display different content based on the state of an element.
Example: Conditional Content
input[type="checkbox"]:checked + label::before {
content: "✓ ";
color: green;
}
input[type="checkbox"]:not(:checked) + label::before {
content: "✗ ";
color: red;
}
In this example, different content is displayed based on whether a checkbox is checked or not.
The content property can be combined with other properties to create advanced effects. Here are a few examples:
Example: Advanced Effects
.element[data-status="active"]::before {
content: "Active - ";
color: green;
}
.element[data-status="inactive"]::before {
content: "Inactive - ";
color: red;
}
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
.blink::after {
content: "⚠";
animation: blink 1s infinite;
color: yellow;
}
In this example, advanced effects such as animated content and dynamic content based on attributes are demonstrated.