8

i have html code

<pre>
line 1
line 2
line 3
</pre>

how can i put some css style to the "lines" inside <pre>, without adding other wrapper into it?

what i mean is something like

pre lines{ color: red}

i'm having difficulties on finding the css selector for that. Thanks in advance.

Lee
  • 3,259
  • 4
  • 21
  • 27
  • What do you mean by "lines" exactly? Why can't you give the color to the pre itself? – Pekka Apr 30 '11 at 07:35
  • @Pekka: What his mean is give different style on each line – Shakti Singh Apr 30 '11 at 07:39
  • @Shakti I'm not sure about that - the example isn't clear – Pekka Apr 30 '11 at 07:40
  • It seems like Lee wants to treat the lines like separate divs or so, for example to color them in zebra stripes or put them in boxes... I don't know any way to do this without inner containers... – opatut Apr 30 '11 at 07:42
  • Yeah, if you want to style each line individually, this is not possible in pure HTML/CSS. The container's contents are a text node, it can't be addressed for styling specifically. – Pekka Apr 30 '11 at 07:45
  • @opatut, yes, that is exactly what i'm up to. it can be easily done using some wrapper, but the problem is, i only have the "pre" (with its content lines) without any wrapper. – Lee Apr 30 '11 at 08:02

2 Answers2

18

You can use this little CSS3 trick, with gradients. This will create automatically, without extra spans, a "zebra" effect:

background: #555;
background-image: -webkit-linear-gradient(#555 50%, #505050 50%);
background-image:    -moz-linear-gradient(#555 50%, #505050 50%);
background-image:     -ms-linear-gradient(#555 50%, #505050 50%);
background-image:      -o-linear-gradient(#555 50%, #505050 50%);
background-image:         linear-gradient(#555 50%, #505050 50%);
background-position: 0 0;
background-repeat: repeat;
background-size: 4.5em 4.5em;

Try different CSS "line-height" so that the text appears correctly.

see: http://www.dte.web.id/2012/03/css-only-zebra-striped-pre-tag.html#.UUoV6lugkoM

benske
  • 3,922
  • 4
  • 24
  • 22
10

If you want add color to all lines in pre, just add

pre {color: red;}

But if you want to add color to some lines, you need extra markup:

<pre>
<span>Line1</span>
line2
<span>Line3</span>
</pre>

pre span {color: red;}
DStereo
  • 251
  • 3
  • 4