Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Apply style to the parent if it has a child with CSS and HTML
Currently, CSS does not have a true parent selector that allows you to style a parent element based on its children. However, there are several modern approaches to achieve similar functionality using CSS and JavaScript.
Syntax
/* Future CSS4 proposal (not yet supported) */
parent $child {
/* styles for parent */
}
/* CSS :has() pseudo-class (modern browsers) */
parent:has(child) {
/* styles for parent */
}
Method 1: Using CSS :has() Pseudo-class
Modern browsers now support the :has() pseudo-class which allows styling a parent based on its children −
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style: none;
padding: 20px;
margin: 10px;
background-color: #f0f0f0;
}
/* Style parent ul if it has a child with class 'highlight' */
ul:has(.highlight) {
background-color: #ffeb3b;
border: 2px solid #f57c00;
}
.highlight {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>Regular item</li>
<li>Another regular item</li>
</ul>
<ul>
<li>Regular item</li>
<li class="highlight">Special item</li>
</ul>
</body>
</html>
Two unordered lists appear. The first list has a gray background. The second list has a yellow background with orange border because it contains a child with the 'highlight' class.
Method 2: Using JavaScript
For broader browser support, you can use JavaScript to add classes to parent elements −
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style: none;
padding: 20px;
margin: 10px;
background-color: #f0f0f0;
}
ul.has-special {
background-color: #e8f5e8;
border-left: 4px solid #4caf50;
}
.special {
color: #4caf50;
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ul>
<li>Item 1</li>
<li class="special">Special Item</li>
</ul>
<script>
// Add class to parent ul if it contains .special child
document.querySelectorAll('ul').forEach(ul => {
if (ul.querySelector('.special')) {
ul.classList.add('has-special');
}
});
</script>
</body>
</html>
Two unordered lists appear. The first has a gray background. The second has a light green background with a green left border because it contains a child with the 'special' class.
Browser Support
| Method | Browser Support |
|---|---|
:has() |
Modern browsers (Chrome 105+, Firefox 103+, Safari 15.4+) |
| JavaScript | All browsers |
Conclusion
While CSS historically lacked parent selectors, the :has() pseudo-class now provides this functionality in modern browsers. For broader compatibility, JavaScript remains a reliable fallback solution.
Advertisements
