josephmccrae
josephmccrae

Reputation: 3

Adding background color only to length of text

I did research this problem and found multiple solutions, but for some reason I'm unable to get these solutions to work for me.

The issue: I am attempting to provide a color background to each line in a multiple-line block of text.

The issue I'm having is this...I have this text (h2) nested inside of a span tag (set with a class), but the entire block is highlighted, not the individual lines of text. I only want the color extending to the end of the text, not the entire text block.

I've included my HTML and CSS. I can't figure out what I'm doing wrong. Here is an example of what I'm looking to do:

http://css-tricks.com/text-blocks-over-image/

HTML:

<h2><span class="lyrics">
"Some come in the form of codependence<br>
A lot of times only end up being codefendants<br>
Ten bucks say they tell for a lower sentence<br>
And leave you up under the jail, begging for a penance<br>
It don't make no sense, what happened to the loyalty?<br>
Honor amongst crooks, trust amongst royalty<br>
I'd rather go out in a blaze, than give 'em the glory<br>
(How many of us have...) a similar story"<br><br>
-??? 
</span></h2>

CSS:

h2 > .lyrics {
background: rgba(0,0,0,0.3);
float: left;
font-family: "Helvetica Neue", Arial, sans-serif;
font-weight: 200;
line-height: 1.5;
margin-left: 50px;
margin-top: 200px;
position: relative;
}

Upvotes: 0

Views: 2348

Answers (2)

Ingvi J&#243;nasson
Ingvi J&#243;nasson

Reputation: 752

Put the margin on the h2 element and remove it from the span element and remove the position relative and the float.

h2 {
margin-left: 50px;
margin-top: 200px;
}

h2 > .lyrics {
background: rgba(0,0,0,0.3);
font-family: "Helvetica Neue", Arial, sans-serif;
font-weight: 200;
line-height: 1.5;
}

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116110

The problem is float: left you applied on the span. It makes it behave like a block. If you remove that (and choose a more visible color), you'll see that it only adds a background color to the lines.

Fiddle: http://jsfiddle.net/31vjg5tf/1/

It does mess with the indenting of the text a little, but I think you can solve that with a proper padding on the h2 instead of a margin on the span.

Fiddle for that: http://jsfiddle.net/31vjg5tf/3/

So basically, you can move the positioning part to the h2. Or most properties actually, although for font and line-height it doesn't matter much where they are. The span is there for the background:

h2 {
  font-family: "Helvetica Neue", Arial, sans-serif;
  font-weight: 200;
  line-height: 1.5;
  margin-left: 50px;
  margin-top: 200px;
  position: relative;
}

h2 > .lyrics {
  background: rgba(0,0,0,0.3);
}

Fiddle bringing that together in your updated minimal code sample:

http://jsfiddle.net/31vjg5tf/4/

Upvotes: 2

Related Questions