<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>纯CSS控制必填标识(红色星号)的隐藏和显示</title> <style> * { margin: 0; padding: 0; outline: none; font-size: 16px; } form { margin: 128px auto; display: flex; flex-direction: column; width: fit-content; } form label { display: flex; align-items: center; margin: 32px; } form label span { min-width: 64px; text-align: right; margin: 0 32px 0 0; } form label input { padding: 8px; } /* 默认隐藏必填标识(红色星号) */ form label span::after { content: "*"; color: red; position: relative; top: 3px; left: 5px; visibility: hidden; } /* 核心代码:显示必填标识(红色星号) */ /* 说 明:选择器“:has(+input[data-required])”的作用是选择紧邻的下一个兄弟元素, */ /* 且该兄弟元素必须是<input>并必须有data-required属性。 */ form label span:has(+input[data-required])::after { visibility: visible; } </style> </head> <body> <form> <label> <span>姓名</span> <input type="text"> </label> <label> <span>手机</span> <input type="text" data-required><!-- 只要设置data-required属性即可自动显示必填标识(红色星号),无需使用JavaScript控制 --> </label> <label> <span>住址</span> <input type="text"> </label> </form> </body> </html>
Copyright © 2025 码农人生. All Rights Reserved