使用CSS自动添加“必填字段”星号以形成输入 [英] Use CSS to automatically add 'required field' asterisk to form inputs

查看:3879
本文介绍了使用CSS自动添加“必填字段”星号以形成输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是克服不幸的事实的好方法,这个代码不会按照预期工作:

What is a good way to overcome the unfortunate fact that this code will not work as desired:

<div class="required">
    <label>Name:</label>
    <input type="text">
</div>

<style>
    .required input:after { content:"*"; }
</style>

在一个完美的世界中,所有需要的输入 s将得到小星号表示该字段是必需的。这个解决方案不可能,因为CSS被插入在元素内容之后,而不是在元素本身之后,但是类似的东西将是理想的。在具有数千个必填字段的网站上,我可以将输入前面的星号移动到一行(:之后),或者我可以将其移动到标签的末尾( .required标签:后),或标签前面,在包含盒子等等...

In a perfect world, all required inputs would get the little asterisk indicating that the field is required. This solution impossible since the CSS is inserted after the element content, not after the element itself, but something like it would be ideal. On a site with thousands of required fields, I can move the asterisk in front of the input with one change to one line (:after to :before) or I can move it to the end of the label (.required label:after) or in front of the label, or to a position on the containing box, etc...

这不仅仅是为了改变我的想法,在哪里放置星号无处不在,表单布局不允许在标准位置的星号。

This is important not just in case I change my mind about where to place the asterisk everywhere, but also for odd cases where the form layout doesn't allow the asterisk in the standard position. It also plays well with validation that checks the form or highlights improperly completed controls.

最后,它不会添加额外的标记。

Lastly, it doesn't add additional markup.

有没有好的解决方案,具有不可能的代码的所有或大部分的优点?

Are there any good solutions that have all or most of the advantages of the impossible code?

推荐答案

类似的结果可以通过使用星号的图片的背景图像并设置标签/输入/外部div的背景和星号图像的大小的填充来实现。
这样的东西:

A similar outcome could be achieved by using a background image of a picture of an asterisk and setting the background of the label/input/the outer div and a padding of the size of the asterisk image. Something like this:

.required input {
   padding-right: 25px;
   background-image: url(...);
   background-position: right top;
}

这将把星号置于文本框内, code> div.required 而不是 .required输入可能更多的是你寻找,如果一点优雅。

This will put the asterisk INSIDE the text box, but putting the same on div.required instead of .required input will probably be more what you're looking for, if a little less elegant.

此方法不需要额外的输入。

This method doesn't require an additional input.

这个帖子。这个答案是OP的权利,但在大多数情况下可能不会是最好的选择。 :之后 styntax是更多更好

I keep getting the odd upvote for this post. This answer was right for the OP but probably won't be the best option in most cases. The :after styntax is much better.

这篇关于使用CSS自动添加“必填字段”星号以形成输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆