Using :empty pseudo-class with :not pseudo-class
Most of the developers don’t know about this CSS trick is using the :empty
pseudo-class in combination with the :not
pseudo-class.
The :empty
pseudo-class targets elements that have no content, including no text, no children, and no whitespace. However, when used alone, it can be limiting.
By combining :empty
with :not
, you can target elements that are not empty, which can be useful for styling elements that contain content.
Example
/* Style elements that are not empty */
div:not(:empty) {
background-color: #f2f2f2;
padding: 10px;
}
In this example, div
elements that contain any content (text, images, etc.) will receive a gray background and 10px of padding.
This trick can be useful for styling elements that need to display content, such as notification boxes or alert messages.