Background color for inline text

In searching for a solution to a CSS problem I had I stumbled over another interesting problem, similar to mine. Most people seemed to agree that it
was impossible to do in pure CSS. The effect those people were after is commonly used in magazines where text with a background color is put over an image. A simple effect hard to achieve.

One solution was to surround each line of text using styled span elements. Another solution used ”a teeny weeny jquery” to solve the problem. I’m sure it’s a solid solution but using jquery and javascript to be able to style text is, well, wrong. Forcing editors to add invisible span elements in text is also not a good idea. But - the effect can actually be achieved using css only and still keep the html simple and semantically correct.

If you use a block element, like <p>, and set the background color, it will be  a filled square behind the text. By setting the css display property to inline you get  close to the effect wanted.

So far it is simple. The problem then is that using padding on inline text will only affect the horisontal padding (text indentation) on the first and last line of text. You get the following effect.

In order to get the effect we want we need to add two elements. A surrounding block element (div) surrounding the paragraph and an inline element (span) surrounding the text inside the paragraph. Both of which is semantically without meaning.

First we add a left border on the surrouding block element. Then we move the text in the span element slightly to the left. The background color is set on the paragraph and does not move. Using this neat little trick we simulate text padding or indentation on each line of text.

Finally we need to fix the vertical padding and line height to get rid of the spacing between the text lines. The end result is not perfect. There are still problems when the user resize text and you need to be careful with the spacing in Internet Explorer. But it’s a good start.

Chrome sometimes change line height seemingly in a random fashion when inserting html <br>. Setting white-space to pre-line fix this behaviour. If not for Internet Explorer it could be simplifed further. Internet Explorer does not seem to support white-space: pre-line. So Internet Explorer still needs manually added html breaks.

The full source

<pre>
<html>
  <head>
  <style type="text/css">
  div#column {
    border-left: 6px solid #000;
  }

  p.subs {
    display: inline;
    font: bold 14px/18px arial;
    color: #fff;
    background: #000;
    padding: 1px 0 1px 0;
    white-space: pre-line; /* Not understood by IE, use manual br for IE */
  }

  p.subs span {
    position: relative;
    left: -3px;
  }

  p.subs br {
    display: none;
  }
  </style>


  <!--[if IE ]>
    <style type="text/css">
      p.subs br {
      display: inline;
    }
    </style>
  <![endif]-->
  </head>
  <body>
    <div id="column">
      <p class="subs"><span>Ground round <br />
salami pig, meatball short loin frankfurter <br />
short ribs pork hamburger rump <br />
strip steak beef ribs T-bone salami ham hock.</span></p>
    </div>
  </body>
</html>
Tagged with: ,
Posted in Web
146 comments on “Background color for inline text
  1. Luigi says:

    Have you ever considered about including a little bit
    more than just your articles? I mean, what you say
    is important and everything. Nevertheless just imagine if
    you added some great visuals or videos to give
    your posts more, “pop”! Your content is excellent but with
    pics and videos, this site could undeniably be one of the most beneficial in its niche.
    Terrific blog!

  2. sbobet asia says:

    Hi to every one, for the reason that I am in fact eager of reading this weblog’s post to be updated on a regular basis.
    It consists of good material.

  3. It’s going to be ending of mine day, except before end I
    am reading this enormous paragraph to improve my experience.

    my site … norton antivirus 360 technical
    support (http://Qr.net/)

  4. Art says:

    Bodybuilding Antagonistic Muscles Exercise Split: In this bodybuilding exercise split, the physique is
    divided over three or 4 days and antagonistic muscles (opposing muscle groups), are
    paired together in each and every bodybuilding exercise.

    One particular Main Muscle Group Per Day Advanced Bodybuilding Workout Split:
    In this bodybuilding exercise split, the body is divided over six days and a single
    main muscle group is targeted in every single bodybuilding workout.
    The back routine below is an instance of how a competitive bodybuilding back routine could appear like.

  5. studied the articles inside of this site loads, going to take
    the leap before long and get a steam shower cabin, in all probability immediately after
    the holiday season

    my web site steam shower whirlpool tub, http://www.fuigoh.jp,

  6. voyance web says:

    Impression des runes gratuit ou bien prophétie de Belline , les possibilités d’obtenir des réponses sont nombreuses dans ça orientation lequel proposition unique des davantage éduqué collection de cariatide.
    La plupart sont à consulter directement là dans ce orientation puis d’autres peuvent
    être appris en suivant les méthodes et ces
    interprétations mises à la texture du lecteur qui pourra
    ces pratiquer à la logement. Des mystères inlassablement pareillement nombreux Certains
    croient ces défunts à la source des télégramme donnés dans seul voyance en direct Les médiums développent leurs aptitudes alors la précision de celles-cela en compagnie de des méthodes
    qui nous déconnectent de la pensée rationnelle. Vous pouvez consulter nos
    chemise sur la pratique du tarot divinatoire, avec à nous partenaire .
    En savoir plus

  7. you’re in point of fact a just right webmaster. The web site loading pace is incredible.
    It seems that you’re doing any distinctive trick. Furthermore, The contents are masterpiece.
    you’ve performed a excellent process in this matter!

  8. What’s Going down i’m new to this, I stumbled upon this I’ve discovered It positively helpful
    and it has aided me out loads. I’m hoping to give a contribution & assist different users like its helped me.

    Good job.

  9. Vi erbjuder dig kontakter med tusentals sexiga singlar och ƿar.

    Snart kommer ɗu att hitta tjejer eller killar som vill
    haa exakt vad Ԁu vill. Vi har många medlemmar
    som är nyfikna, villiga och kåtɑ, träffa någon av dem redan idag.

  10. Arnold Schwarzenegger talks about why he cares about climate modicy and explains his worldwide
    crusade to make an influence. Arnold Schwarzenegger and the Snake
    River Hotshots behind the scenes for The End of The Woods.

  11. Daryl says:

    Hello there Your main website starts up really slow if you ask me, I not really know
    who’s problem is that on the other hand wikipedia opens up quite quick.
    Anyways, Thank you for placing such a brilliant blog post.
    I do believe it has been incredibly useful to user who seem to visit here.

    I really hope I will be able to get a lot more amazing things and
    I also should certainly compliment by telling you have carried out good job.
    To get additional knowledge through articles that you write-up,
    I actually have saved to bookmarks this page.

  12. I аm aϲtually delighted tߋ glance at thiѕ webloog posts whijch
    carries lots οf valuable іnformation, thanks for providing ѕuch statistics.

  13. Kazuko says:

    An impressive share! I have just forwarded this onto a friend
    who has been doing a little research on this.
    And he in fact ordered me dinner due to the fact that I stumbled
    upon it for him… lol. So let me reword this….
    Thank YOU for the meal!! But yeah, thanks for spending some time to talk
    about this matter here on your web page.

  14. You are able to also select to joun affiliate programs which
    have products or services your own visitors could well be interested in and additionally promote them on your blog.
    There iss nothing wrong with wanting to make money online.

    Writing content iss probably thhe most popular way oof making money
    online.

    my web page internet marketing ninjas seo tools

  15. The standard security provided by Acrobat PDF consists
    of two different methods and two different passwords, “user password” and “owner password”.
    3D Skyrocket stands out from other fireworks wallpapers because is uses Open GL for the visuals.
    With the wireless off, battery life is up to 14 hours and up to approximately 4 hours for video or pictures, all of which
    is similar to earlier rumors and informal comments.

  16. If you desire to improve your knowledge only keep visiting this website and be
    updated with the most recent news update posted here.

  17. read this says:

    I am genuinely thankful to the holder of this web site who has shared this impressive post at at this
    place.

  18. My brother suggested I might like this blog.
    He was totally right. This post actually made my day. You
    cann’t imagine simply how much time I had spent for this info!
    Thanks!

  19. Howdy! I know this is kinda off topic however I’d figured I’d ask.

    Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
    My site goes over a lot of the same subjects as yours and I believe we could greatly benefit from each other.

    If you’re interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Superb blog by the way!

  20. sniper says:

    Thanks designed for sharing such a nice idea, article is pleasant, thats why i have read it completely

  21. What’s up to all, how is the whole thing, I think every one is getting more
    from this web page, and your views are good designed for new people.

  22. I have been exploring for a little for any high quality
    articles or blog posts in this sort of area . Exploring in Yahoo I
    at last stumbled upon this site. Studying this info So i’m happy to express that I’ve an incredibly excellent uncanny feeling I came upon just what
    I needed. I so much undoubtedly will make certain to don?t put out of your mind this
    website and provides it a look on a constant basis.

  23. Car Security says:

    Excellent goods from you, man. I’ve be aware your stuff prior to and you
    are simply too wonderful. I really like what you’ve got here, really like what you are saying and the way wherein you say it.
    You’re making it enjoyable and you still take
    care of to stay it smart. I cant wait to read much more from
    you. This is actually a wonderful site.

  24. When I initially commented I clicked the “Notify me when new comments are added” checkbox
    and now each time a comment is added I get several e-mails with the same comment.
    Is there any way you can remove me from that service?
    Thank you!

  25. My warden was practically untouchable after I put him in it and you’ll also find some nice accessories along the way.

    She added her perspective and insight to this tale; she also shared with me
    some history, and we had a great discussion about what is the nature of truth.
    This package included all franchise agreements, loan agreements, trade mark registrations, etc.

    My web-site Game Of War Fire Age Hack; maiersbaeckerei.de,

  26. You might spend very little for the purchase of your food processor, but if
    it doesn’t accomplish the functions you need it to do or even worse that it breaks
    down in a matter of a few months utilizing it, after this you could end up obtaining one more unit which will in the end cost you more money.
    Disc Playback Modes: A-B Repeat, Angle, PBC, Slow Motion, Zoom, Disc
    Menu, Fast Backward, Fast Forward, OSD, Parental control, Resume Playback from Stop.
    Peel the pepper, cut off the top and remove the seeds and membrane.

  27. It’s remarkable in support of me to have a website, which is valuable in support of my knowledge.
    thanks admin

  28. Pretty nice post. I just stumbled upon your blog and
    wanted to say that I have really enjoyed surfing around your blog posts.
    After all I’ll be subscribing to your rss feed
    and I hope you write again soon!

  29. Koku Tespiti says:

    Hi there! This is my 1st comment here so I just wanted to give a quick shout out and tell you I really
    enjoy reading through your articles. Can you suggest
    any other blogs/websites/forums that cover the same topics?
    Thank you!

  30. I’m amazed, I have to admit. Rarely do I come across a blog that’s both educative and engaging, and let me tell you, you’ve hit the nail on the head.
    The problem is something which not enough men and women are speaking intelligently about.

    Now i’m very happy I came across this during my hunt for something regarding this.

  31. ike Free Run says:

    I am really happy to glance at this webpage posts which
    carries tons of helpful data, thanks for providing these statistics.

  32. Tremendous things here. I’m very glad to see your
    post. Thank you a lot and I’m having a look ahead to touch you.
    Will you kindly drop me a e-mail?

    My page – forex robot in urdu [queenstreetveterinaryservices.com]

  33. smoke says:

    Otherwise you end up having to constantly relight it during consumption. A head gasket failure results
    in a leak, which in turn produces white smoke.
    Rights of Physically Challenged Occupants – Renters with particular physiological disabilities may have other legal solutions at
    their disposal to cease drifting smoke from coming into
    their domiciles.

  34. Amazing things here. I’m very happy to peer your article.
    Thanks a lot and I am looking forward to contact you. Will
    you kindly drop me a e-mail?

  35. Weaves as well as extendables are made use of
    for a mixture of purposes, and are able to include adding volume too thinning hair,
    or looking at brand-new hairstyles that would be actually inconceivable
    to create within the limitations off natural hair alone.
    There are different versions of haqir makeover gaqmes that girls annd women can play.
    Hairweaves assist in adding fashion coloors to your existing
    natural hairs without use of chemicals.

  36. lintas.me says:

    No one carries around their laptops or computers with them all day, but their phone is with them at all times.
    If you are a normal cell phone user considering making the jump to a
    smartphone, you are probably interested in learning about some of the features
    that smartphones offer, before deciding whether or not the
    upgrade is worth it. 1] Flipboard Flipboard application is considered as personal favorite app of Steve Jobs.

  37. Very energetic blog, I liked that bit. Will there be a part 2?

    My blog … hiking boots or shoes

  38. It’s nearly impossible to find educated people on this topic,
    however, you seem like you know what you’re talking
    about! Thanks

    รู้สึกอิสระที่จะเยี่ยมชมเว็บไซต์-ราคามือถือ

  39. Dust is the biggest concern when cleaning dollhouse furniture.

    Working without one will save you a great deal of time and
    money. Along with elegance it also makes the room warm and welcoming for the residents as well as the guests.

  40. Great info. Lucky me I recently found your blog by chance (stumbleupon).
    I have book marked it for later!

  41. Emilie says:

    Valuable info. Lucky me I discovered your website by chance, and
    I am surprised why this coincidence didn’t came about in advance!
    I bookmarked it.

  42. What’s up friends, good article and nice arguments commented
    here, I am genuinely enjoying by these.

  43. Thanks for one’s marvelous posting! I truly enjoyed reading it, you may be a
    great author.I will be sure to bookmark your blog and will come back someday.

    I want to encourage yourself to continue your great work, have a nice morning!

  44. Hello Dear, are you in fact visiting this web page on a regular basis,
    if so then you will definitely take good know-how.

    my page; pc maintenance software

  45. I’d like to thank you for the efforts you’ve put in writing this website.
    I really hope to see the same high-grade content from you later on as well.
    In fact, your creative writing abilities has motivated me to get my very own website now ;)

  46. Iva says:

    bookmarked!!, Ireally like your blog!

    Also visit my blog post :: buy basketball clothing online –
    Iva -

2 Pings/Trackbacks for "Background color for inline text"
  1. [...] Background Color for Inline Text - This tutorial shows how to add a background color to text using only CSS. [...]

  2. [...] Background Color for Inline Text - This tutorial shows how to add a background color to text using only CSS. [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>