在<pre> block to extend to full line width (set by container)

时间:2016-10-15 16:55:52

标签: html css

I use <span> tags to highlight some parts of pre-formatted text by setting it's background colour. If the <span> contains a line-break, the selected background colour stops at the last character before the line-break, and continues on the next line. Instead I would like the background colour to extend to the full width of the container. How could I achieve this (preferably using CSS only)?

Example:

<pre style="width: 20ex;background:gray">
A B <span style="background:red">C
D E</span> F G H
</pre>
Here, the red background behind C should extend all the way to the right.

2 个答案:

答案 0 :(得分:1)

定位的伪元素可以做到这一点。

&#13;
&#13;
pre {
  margin: 1em auto;
  overflow: hidden; /* required */
}

pre span {
  position: relative;
  z-index: 1;
}

pre span::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 1.2em; /* whatever your line-height is */
  width: 50em; /* some arbitrary large width*/
  background: inherit;
  z-index: -1;
}
&#13;
<pre style="width: 20ex;background:gray">
A B <span style="background:red">C
D E</span> F G H
</pre>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

you can do it like this

<pre style="width: 20ex;background:gray">
A B <span style="background:red;display: block;">C
D E</span> F G H
</pre>