Coder Perfect

Inserting text with CSS


CSS is new to me, but I’ve already used it to change the style and formatting of text.

I’d like to utilize it now to put the following text:

<span class="OwnerJoe">reconcile all entries</span>

Which I’m hoping to be able to show as:

Joe’s task is to reconcile all of the entries.

That is, I want the sentence Joe’s Task: to be displayed solely because I am of the class “Owner Joe.”

I could do that with the following code:

<span class="OwnerJoe">Joe's Task:</span> reconcile all entries.

However, specifying both the class and the content seems a bit superfluous.

Is it possible to achieve what I’m after?

EDIT One option is to make it a ListItem li> with the words “Joe’s Task” as the “bullet.” I saw examples of how to define different bullet styles and even bullet images. Is it possible to make the list-bullet out of a small block of text?

Asked by abelenky

Solution #1

It is, but it requires a browser that supports CSS2 (all major browsers, IE8+).

.OwnerJoe:before {
  content: "Joe's Task:";

However, I would suggest utilizing Javascript instead. Using jQuery:

$('.OwnerJoe').each(function() {
  $(this).before($('<span>').text("Joe's Task: "));

Answered by Marcel Jackwerth

Solution #2

Everyone appears to appreciate the jQuery solution, however it has a fundamental flaw: it is not scalable (at least as it is written). Martin Hansen, I believe, has the proper concept in using HTML5 data-* attributes. You can even correctly utilize the apostrophe:


<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>


div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }


Joe's task - mop kitchen
Charles' task - vacuum hallway

Answered by Jeff

Solution #3

Also look into the CSS content attribute’s attr() method. It creates a text node from one of the element’s attributes. Use it in the following way:

<div class="Owner Joe" />

div:before {
  content: attr(class);

Alternatively, you might use the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);

Answered by Martin Hansen

Solution #4

Simply code it as follows:

    .OwnerJoe {
      //other things here
        content: "Joe's Task: ";

Answered by BartSabayton

Solution #5

Although I realize this is an old question, I’d like to update the response to CSS3. It’s a pseudo-class or a pseudo-element that’s in doubt.

CSS2 way (pseudo-class)

    .OwnerJoe:before {
      content: "Joe's Task:";

The CSS3 way (pseudo-element) Take notice of the double colon.

    .OwnerJoe::before {
      content: "Joe's Task:";

Answered by Joe Johnston

Post is based on