Home  >  Q&A  >  body text

Using Tailwind CSS to change the style of a parent div in response to the selected state of a radio button

<p>I have a table with multiple columns and a radio button per row. I need to change the background color of the entire row when I select a specific button. Can this be achieved? </p> <pre class="brush:php;toolbar:false;"><tr class="flex items-center p-4 space-x-4 border hover:bg-indigo-50"> <input type="radio" name="user" id="{{ user.id }}"> <label for="{{ user.id }}">{{ user.email }}</label> <div>{{ user.name }}</div> </tr></pre> <p>In Tailwind, you can use the "peer" class to style adjacent blocks. But I need to style the parent block (when the <input> is selected, the background color of the parent block should change). </p>
P粉718165540P粉718165540452 days ago565

reply all(1)I'll reply

  • P粉958986070

    P粉9589860702023-08-16 21:48:18

    You can use the pseudo-class :has(), but its support in browsers is limited (for example: Mozilla does not support it). You can check the browser support of this selector.

    tr:has(input:checked){
        background: green;
    }
    <script src="http://cdn.tailwindcss.com"></script>
    
    <table>
        <tr class="flex items-center p-4 space-x-4 border hover:bg-indigo-50">
            <td>
                <input type="radio" name="user" id="{{ user.id }}">
                <label for="{{ user.id }}">{{ user.email }}</label>
                <div>{{ user.name }}</div>
            </td>
        </tr>
    </table>

    reply
    0
  • Cancelreply