CSS3:带输入的伪元素之后

时间:2010-12-06 18:52:08

标签: css css-selectors

只需使用:before:after

似乎我无法在/ input按钮上使用它们?以为我可以使用它确实为必填字段显示星号。不一定是我要做的,只是一个选项

input {
    position: relative;
}
input:after {
    content: ''; 
    background: url(accept.png) 0 0 no-repeat; 
    height: 16px; 
    position: absolute; 
    right: -20px; 
    top: 5px; 
    width: 16px;
}

相同的代码在li

上正常工作
li {
    clear: both; 
    margin: 0 0 10px; 
    position: relative;
}
li:after {
    content: ''; 
    background: url(accept.png) 0 0 no-repeat; 
    height: 16px; 
    position: absolute; 
    right: -20px; 
    top: 5px; 
    width: 16px;   
}

5 个答案:

答案 0 :(得分:12)

我也认为同样的事情会有用,但是,我能够让前/后伪元素工作可靠的最简单方法是将输入包装在一个SPAN标记,并将一个类应用于该标记。

此讨论提供了一些有关input:after不起作用的见解: http://forums.mozillazine.org/viewtopic.php?f=25&t=291007&start=0&st=0&sk=t&sd=a

您可以执行以下操作:

.required:after {
    content: "REQUIRED";
    color: orange;
    margin-left: 1em; /* space between the input element and the text */
    padding: .1em;
    background-color: #fff;
    font-size: .8em;
    border: .1em solid orange;
}

<span class="required"><input id="foo" /></span>

答案 1 :(得分:6)

这里提出了一个基本相同的问题,有一个很好的解释:https://stackoverflow.com/a/4660434/749227

总而言之,输入不是容器,也不能有子容。因此,通常不能将:before和:after伪元素插入的内容插入到输入中。

请注意,您可以使用<input type="submit|button">而不是<button>来使用可以生成孩子的{{1}},因此,对于该输入,我们可以使用“{1}}解决方案。 (好吧,如果你能控制标记;)

答案 2 :(得分:2)

我只是看了同样的事情 - 只是我想用它来显示accesskeys:

*[accesskey]:after {
     content:' [' attr(accesskey) ']';
}

不太热衷于编写多个地方的accesskey值,这通常会增加不保持值相同的风险,并且可能是明智的UE-wise = 0 /

答案 3 :(得分:1)

这个答案(该行下面的文字)不起作用(对于基于文本的input无论如何),但是它会因为它节省的机会而留在原地别人打算用同样的方法来达到同样的最终结果。执行此操作的唯一方法是,@Tim notes, in his answerinput(或其他)元素包装在另一个元素中,例如span,然后将样式 使用:after伪元素。

JS Fiddle demo of a working example


嗯,他们似乎工作得很好JS Fiddle demo,除了position: absolute :after内容出现在元素本身内(按钮内部或复选框等)

HTML:

<button class="req">button</button>
<input class="req" type="text" />
<input class="req" type="radio" />
<input class="req" type="checkbox" />
<textarea class="req"></textarea>

的CSS:

input,
textarea {
    display: block;
}
.req {
    position: relative;
}

.req:after {
    content: "*";
    margin: 0 0 0 0.5em;
    position: absolute;
    top: 0;
    right: -1em;
}

答案 4 :(得分:0)

我需要使用输入执行此操作,但无权更改由Wordpress和Jquery生成的html。好吧,也许我可以,但这将是一个长期的解决方法。同样的原因:可访问性。

因此,您可以使用一种可能的解决方法:

#comment-form input[type=text],
#comment-form input[type=email],
#comment-form input[type=url],
#comment-form input[type=password] {
width:40%; margin-right:60%; }

如果出现错误信息,则它不再适合同一行&amp;碰到了。当然,你需要考虑是否可以在布局中支持百分比宽度,但是你明白了。