首页 > 解决方案 > 如何通过css选择所有输入元素?

问题描述

下面的 css 代码是重复的,是否有任何 css 快捷方式,所以我们可以在单行代码中选择所有输入字段。

.form-group input[type='text'],
.form-group input[type='email'],
.form-group input[type='password'],
.form-group input[type='tel']  
{
   margin:10px; 
}

标签: htmlcssformscss-selectorsfrontend

解决方案


假设您的 HTML 结构如下所示:

<div class="form-group"> // or any other kind of wrapper element with a class of "form-group"
  <input type="text">
  <input type="email">
  <input type="pasword">
  <input type="tel">
</div>

您可以将当前的 css 替换为以下内容:

.form-group input { margin:10px; }

无论输入类型如何,边距都将应用于<input>嵌套在元素内的所有元素。.form-group

检查并运行以下代码片段以获取上述代码的实际示例:

.form-group input { margin:10px; }
<div class="form-group">
  <input type="text">
  <input type="email">
  <input type="pasword">
  <input type="tel">
</div>


推荐阅读