As others have stated, this cannot be done purely through CSS. However, here's a JavaScript solution. This assumes you're using jquery 1.4.1+ (probably works with many versions, but this is the one I tested with).
This is a bit clunky, but it will allow you to apply a style to text selected by mouse input only while it is selected. A quick explanation of the functions:
- reset() removes the styling from any existing selections and gets rid of the extra spans
- highlight() wraps the selection in a new span node and applies the style
- getSelected() just returns the selection object. Note that reset() does nothing if you right-click; this is to allow the right-click menu to appear. If you right-click outside of your selection, you won't get the results you're looking for, but that can probably be fixed.
Let me know if you want more detail. Sorry for the huge code block.
<script type="text/javascript">
$(document).ready(function () {
$(document).mousedown(reset);
$(document).mouseup(highlight);
});
reset = function (e) {
var st = getSelected();
if (st != '') {
if (e.which != 3) {
$("span").contents().unwrap();
}
}
};
highlight = function () {
var st = getSelected();
if (st != '') {
var newNode = document.createElement("span");
newNode.setAttribute("class", "selectionClass");
var range = st.getRangeAt(0);
range.surroundContents(newNode);
st.selectAllChildren(newNode);
}
};
getSelected = function () {
var selection = '';
if (window.getSelection) {
selection = window.getSelection();
} else if (document.getSelection) {
selection = document.getSelection();
} else if (document.selection) {
selection = document.selection.createRange().text;
}
return selection;
};
</script>