SCSS实现:若孙子元素含selected类,为祖父tr设置样式
Hey there! I've got you covered. To style the <tr> element whenever it contains a <div> with the selected class, here's a straightforward SCSS implementation tailored to your HTML structure:
SCSS Code
// Optional: Add base table styles for better presentation table { width: 100%; border-collapse: collapse; margin: 1rem 0; } td { padding: 0.5rem; border: 1px solid #eee; } // The core style targeting the row with a selected div tr:has(.selected) { background-color: #f0f8ff; // Pick your preferred background color } // Optional: Highlight the selected div itself for clarity .selected { font-weight: 600; color: #2563eb; }
How This Works
- The
:has()pseudo-class is the key here.tr:has(.selected)selects any<tr>that has a descendant element with theselectedclass (your<div>inside a<td>). This is exactly what you need to target the correct row. - With your provided HTML, the first
<tr>will get the background color because it contains the selected<div>, while the second row remains unstyled.
Quick Compatibility Note
:has() is supported in all modern browsers (Chrome, Firefox, Edge, Safari). If you need to support older browsers (like Internet Explorer), you'd need a JavaScript fallback to add a class to the row, but for most modern projects, this SCSS solution works out of the box.
内容的提问来源于stack exchange,提问作者Ismael
相关产品推荐
相关产品推荐

