<input>获得焦点时修改其父元素背景色

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><input>获得焦点时修改其父元素背景色</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            font-size: 16px;
        }

        .parent {
            width: fit-content;
            height: fit-content;
            margin: 250px auto;
            padding: 30px;
            background: #d9d9d9;
            transition: 500ms; /* 完成过渡效果时长,对于“:focus-within”伪类同样有效 */
        }

        /* 核心代码:使用“:focus-within”伪类 */
        .parent:focus-within {
            background: #cce8ff;
        }

        input {
            display: inline-block;
            outline: none;
            padding: 5px;
            border: 5px solid black;
        }

        input:focus {
            border-color: red;
        }
    </style>
</head>
<body>
<div class="parent">
    <label>姓名:<input type="text"></label>
</div>
</body>
</html>

Copyright © 2025 码农人生. All Rights Reserved