Friday

A different line-through color

Ever tried styling a line-through price so the strike color is different than the text? You know when you're looking at a sale online and the thing you're looking at is something like 20% off, and the merchant shows you a "before" price that has a horizontal line through it? This can be achieved in CSS using the line-through value on the text-decoration property. By default, it puts a line-through your text which is the same color as the font in that element. But what if you wanted a different color for the line than you have for the text (e.g. a red line through black text)? Turns out you can't style that separately in CSS; i.e. there's no support for something like line-through-color...But interestingly enough, you can add a bit of HTML structure around your text (price in our example), and this structure will allow you to style things uniquely. To wit:

Example HTML


    $515.00

Example CSS

.strikethrough {
    text-decoration: line-through;
    color: red;
}

.strikethrough * {
    color: #000;
}

Rendered Example

Buggy Behavior?

Pretty sweet. I wonder why it works this way though, because we are adding text-decoration to a container that doesn't actually have any text in it. Sure it's child has text, and we know that rules will be inherited by their children, but the line-through is working on the child DESPITE the child's inheritance of line-through. That is, the parent line-through is working on it's child's text, while the child's text is NOT actually applying a line-through at all. In fact, I can show this by setting my child to text-decoration: none, and yet the line-through still works on the parent. I find this odd, but oddly satisfying. This behavior is very nearly a bug in my opinion, though it's also a nice (maybe unintentional) feature. This goes way back to CSS1, so I think we're good. Here's some of my additional testing to see if this behaved differently with block or inline element combinations...turns out the answer is no. :-)

Support

Seems pretty good - I'm seeing very little support information for this feature on any of the usual boards (e.g. caniuse, quirksmode, sitepoint), but I've tested in FF, Chrome, IE7+, and all work similarly, and as expected. Mozilla claims support back to IE3 (IE3!), so it seems this is pretty ubiquitous in terms of support.

2 comments:

  1. Nice trick. But when you set float to the inner span, it breaks...

    ReplyDelete
  2. That's true, though I can't think of a use case where you'd need to float the inner span; after all, we're just adding a bit of markup for a very specific, and inline case.

    ReplyDelete