Using :before With Option Element In A Drop Down List
Solution 1:
You should be using a <label>
to indicate what the <select>
is for. You cannot use pseudo-elements on <option>
elements because only <option>
elements are valid within a <select>
. The other reason you wouldn't want to do this is because pseudo-elements are typically skipped by screen readers, making the label non-accessible to a portion or the population and certain assistive technologies.
This is the proper way to associate a label such as "Sort by" with a drop down list:
<label>
Sort by:
<select><option>one</option><option>two</option></select></label>
or
<labelfor="my-select">Sort by: </label><selectid="my-select"><option>one</option><option>two</option></select>
If you require "Sort by: " within the drop-down list, you should add that label within the HTML or inject it with JavaScript as CSS cannot do this. I would suggest arguing that it is not the right way to go with your designer however as you will have a bunch of redundant text and the drop-down will just look ugly.
This is how you would go about injecting the label within the drop-down using jQuery:
$('option').each(function () {
$(this).text("Sort by: " + $(this).text());
});
Solution 2:
In the CSS 2.1 spec, the :before
pseudo-element is somewhat vaguely defined, and it says: “Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” Although option
is not empty like input
, it is still rather special. There is no clarifying definition in newer CSS specs.
In practice, browsers mostly ignore :before
and :after
for control elements like select
and their children. Testing with Firefox, IE, Chrome shows that currently only Firefox implemens option:before { content: ... }
, and only when the select
element is “open” (either focused so that the option list is opened or has a size
attribute with a value larger than 1).
So the approach is not feasible, and you should consider a better way to deal with the ultimate problem. Apparently, you have already found out that a visible label is to be preferred to using generated content.
Post a Comment for "Using :before With Option Element In A Drop Down List"