CSS :empty
The CSS :empty pseudo-class targets elements that do not have any child elements or text content. It is useful for styling placeholders or empty containers in your layout.
The syntax for the :empty
pseudo-class is:
</>
Copy
selector:empty {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The element you want to target. |
property | The CSS property to apply. |
value | The value assigned to the CSS property. |
Examples
1. Highlighting Empty Paragraphs
In this example, empty <p>
elements are styled with a red border.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
p:empty {
border: 1px solid red;
}
</style>
</head>
<body>
<p>This paragraph has content.</p>
<p></p>
</body>
</html>
2. Styling Empty Divs
Here, empty <div>
elements are styled with a gray background and italic text to indicate they are placeholders.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div:empty {
background-color: lightgray;
font-style: italic;
height: 50px;
width: 200px;
}
</style>
</head>
<body>
<div></div>
<div>This div has content.</div>
</body>
</html>
3. Styling Empty List Items
In this example, empty <li>
elements are styled with a yellow background to make them noticeable.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
li:empty {
background-color: yellow;
}
</style>
</head>
<body>
<ul>
<li>List item 1</li>
<li></li>
<li>List item 3</li>
</ul>
</body>
</html>
4. Indicating Empty Table Cells
Here, empty <td>
elements are styled with a red border to indicate missing data.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
td:empty {
border: 2px solid red;
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<table border="1">
<tr>
<td>Data 1</td>
<td></td>
<td>Data 2</td>
</tr>
</table>
</body>
</html>
5. Styling Empty Spans
In this example, empty <span>
elements are styled with a green border.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
span:empty {
border: 1px solid green;
display: inline-block;
width: 50px;
height: 20px;
}
</style>
</head>
<body>
<span></span>
<span>I have content</span>
</body>
</html>