0

Sorry, weird title.

Anyway, I add a div and some text to a Control like so, in C#.

lit.Text = "<div class=\"event\">" + text + "</div>";

And I style it like this:

.event:hover  
{
    background: #F0F0F0;
}

I'd like the background change to only be as long as the text, not the whole div. How can I do this?

UPDATE: Wrapping it in a span and styling the span works to an extent. I didn't mention that the control I'm adding it to is a table cell. I've got:

style="width:50%"

which was forcing the cell to take up exactly half the table, despite how much text was in it or the second cell in the same row. With the span, this is no longer true and the table is misaligned. How do I fix that?

Jeremy
  • 5,365
  • 14
  • 51
  • 80
  • You can't; text can't be targeted with CSS unless it's wrapped in an element (`b`, `a`, `em`, `span`...). – David Thomas Jun 12 '11 at 19:36
  • If I understand correctly, the div class 'event' has to be 50% width to format the cell correctly, right? If so, see my updated answer, else please explain it better – Damien Pirsy Jun 12 '11 at 19:54

4 Answers4

1

Than you have to apply it to the text.

lit.Text = "<div class=\"event\"><span>" + text + "</span></div>";

    .event 
    {
      width:50%;
    }


    .event span:hover  
    {
        background-color: #F0F0F0;
    }

Should do the trick;

Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
1

If you want the width of the div to be only as wide as the content (and not have only the background as wide as the content), then I would suggest reading through this question.

If you want only the background to be as wide as the text, then wrap the text in another element (such as a span) and set the background on that instead.

Community
  • 1
  • 1
James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

I'm not entirely sure what you're after but maybe:

lit.Text = "<div class=\"event\"><div>" + text + "</div></div>";

with CSS:

.event:hover > div
{
    background: #F0F0F0;
}

or possibly instead:

lit.Text = "<div class=\"event\"><span>" + text + "</span></div>";

with CSS:

.event:hover > span
{
    background: #F0F0F0;
}
thirtydot
  • 224,678
  • 48
  • 389
  • 349
1

You have to wrap your text in an inline element like span :

lit.Text = "<div><span class=\"event\">" + text + "</span></div>";
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297