如何使用CSS在占位符中获取星号

2024-02-15

I want to add an asterisk mark to placeholder of inputs. Something like this: enter image description here

我已经搜索过互联网但找不到有效的解决方案。

我目前的做法:

目前我正在尝试将其添加到 after 伪元素中,但没有出现。

    input[type=text]::-webkit-input-placeholder:after {
       content: '*';
       color: red; vertical-align: top; font-size: 10px;
    }
    
    input[type=text]:-moz-placeholder:after { /* Firefox 18- */
       content: '*'; 
       color: red; vertical-align: top; font-size: 10px;
    }
    
    input[type=text]::-moz-placeholder:after {  /* Firefox 19+ */
       content: '*';
       color: red; vertical-align: top; font-size: 10px;
    }
    
    input[type=text]:-ms-input-placeholder:after {  
       content: '*';
       color: red; vertical-align: top; font-size: 10px;
    } 
<input type="text" name="your-name" placeholder="Naam">

我不想直接在占位符中添加符号。但会喜欢它以任何其他方式让我以不同的方式设计符号。(假设我想要我的符号为蓝色,但其余文本为灰色)。

因此,如果有人可以帮助我在占位符中添加一个星号。

JSFIDDLE https://jsfiddle.net/KiranKumarDash/987tybdg/1/


为什么不在占位符属性本身中简单地使用 * 呢?

.asterisk::-webkit-input-placeholder {
    color:    #f00;
}
.asterisk:-moz-placeholder {
   color:    #f00;
   opacity:  1;
}
.asterisk::-moz-placeholder {
   color:    #f00;
   opacity:  1;
}
.asterisk:-ms-input-placeholder {
   color:    #f00;
}
<input type="text" name="your_name" placeholder="*" class="asterisk" />

EndNote:不能在中使用伪元素替换了 html 元素 https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element


根据您的评论,您还可以使用 required 属性,然后像这样设置它们的样式:

<input type="text" name="your_name" placeholder="*" required />
[required]::-webkit-input-placeholder {
    color:    #f00;
}

根据您的下一个评论要求,您需要将需要星号的输入包装在如下所示的范围内:

.input-group{
  position: relative;
}
.input-group::after{
  content: '*';
  position: absolute;
  top: 3px;
  left: 46px;
  color: #f00
}
<span class="input-group">
  <input type="text" name="your_name" placeholder="Naam" />
</span>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用CSS在占位符中获取星号 的相关文章