简体   繁体   English

如何仅使用css在标签的第一个字母前放置一个“必需的星号”图像?

[英]How would you place a 'required asterisk' image in front of the first letter of a label using only css?

Is it possible to place a 'required asterisk' image in front of the first letter of a label only using css? 是否可以仅使用css在标签的第一个字母前面放置一个“必需的星号”图像? The text of the label is right aligned, so there is a varying length of space in front of the text of each label. 标签的文本是右对齐的,因此每个标签的文本前面都有不同的空间长度。

.foo:before {
    content : "* ";
    color   : red;
}

It is possible with some CSS, but it won't work with IE. 有可能使用一些CSS,但它不适用于IE。 First, you need to create a bulleted list. 首先,您需要创建项目符号列表。

Next, hide the list-item-bullet: 接下来,隐藏list-item-bullet:

ul > li {
    list-style-type:none;
    list-style-position:inside;
}

then add a new symbol in front of the list-item: 然后在list-item前面添加一个新符号:

ul > li:before {
    content:"*  ";
}

If you wish to place an image using CSS, without modifying content, then you need to use a background image, eg 如果您希望使用CSS放置图像而不修改内容,则需要使用背景图像,例如

label {
  padding-left: 12px;
  background: url(asterisk.png) no-repeat;
}

This implies an accessibility problem: people using nonvisual browsing won't get the information about requiredness, since there is no way to specify a textual alternative to a background image. 这意味着可访问性问题:使用非可视浏览的人将无法获得有关必需性的信息,因为无法指定背景图像的文本替代方法。

On the other hand, to limit the effect to only such labels that relate to required fields, you would need to use a class selector, say label.required , and add a class attribute to the relevant label elements. 另一方面,要将效果限制为仅与必需字段相关的标签,您需要使用类选择器,例如label.required ,并将class属性添加到相关label元素。 Then I suppose you could just as well modify the content by adding an actual image before the relevant label elements, without resorting to CSS, eg 然后我想你也可以通过在相关label元素之前添加实际图像来修改内容,而不需要求助于CSS,例如

<img src=asterisk.png alt="Required "><label ...

Just use padding . 只需使用padding

<label for="required"><span>Required</span></label> 
<input type="text" name="required" id="required" />

CSS: CSS:

label {
    text-align: right;
    width: 200px;
    vertical-align: middle;
    display: inline-block; }
label span {
    background: url(http://placehold.it/5x5) 0 0 no-repeat;
    padding: 0 0 0 6px;
    vertical-align: middle;
    display: inline-block; }
input {
    vertical-align: middle;
    display: inline-block; }

Preview: http://jsfiddle.net/Wexcode/j475V/1/ 预览: http//jsfiddle.net/Wexcode/j475V/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM