7

If you check the form at this link, you'll see that required fields have a class="required" in the CSS and a * in the markup.

http://drupal.org/user

Can the * which shows in the markup be added entirely with CSS for divs that have this class?

1
  • Removed php tag. No PHP here… Commented Jan 12, 2011 at 21:05

5 Answers 5

12

You can use the after pseudo class:

.required:after { content: "*"; }

or, because you explicitly asked for a div with that class:

div.required:after { content: "*"; }

Should work (for IE only since IE8)


You can apply any style to this, of course. You can even do things like this:

div.required:after:hover { /* Hello, I'm a geek. */ }

This can also be achieved with JavaScript. jQuery:

$(".required").append("*");
Sign up to request clarification or add additional context in comments.

Comments

2
span:after { content:"*"; }

Demo: http://jsfiddle.net/W3gHU/

Comments

2

You can use the :after or before css pseudo element for this, more info, also abt which browsers support it here.

Comments

1

You could add an image of a star via CSS. This should work in all browsers.

.required
{
background-image:url(/path/to/your/images/dir/required-field.png);
background-position:top right;
background-repeat:no-repeat;
padding-right:10px;
}

Comments

1

Try this page:

<html>

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

<body>

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

</body>

</html>

:after is understood by probably everything except for IE (hopefully IE9 will have support)

Update taking into account comment of Šime Vidas: it was just example of using. Of course it would bring more sense if we make it this way:

.required:before {
    color: red;
    content: "*"
}
....
<div>Name <input type="text" class="required"> </div>

then we can even add unobtrusive javascript validation to that field (so this way brings good advantages). The problem is that this refactored page will be displayed as we want it only in Opera (I checked it on all last builds of browsers, except for FireFox 4, but I'm not sure FF will change the way they take that style into account).
:after and :before do not work for input and img elements; there is related discussion of why. $(".required").before("*") from jQuery however will work everywhere, but that's more about JavaScript then CSS (and was mentioned before by other people).

1 Comment

It would make more sense if you'd put the INPUT elements inside the DIVs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.