我可以调整<pre>区域的宽度以适合文本吗?

Gor*_*don 20 css

我有以下内容:

<p>This is a test</p>
<pre>public class Car {
    protected Car() { }
    protected Car(int speed) { }
    protected void Car() { }
}</pre>
<p>Another line</p>
Run Code Online (Sandbox Code Playgroud)

pre {
    font-family: monaco,consolas,"courier new",monospace;
    font-size: 1em;
    min-height: 3em;
    overflow: auto;
    padding: 1em;
    xwidth: 80%;
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

当文本显示<pre>背景时,页面的整个宽度.我在这里有一个演示:

小提琴

我想要的是红色背景在我的代码最右边的字符之后停止.我不希望看到从页面的一侧延伸到另一侧的大红色区域.

有人能告诉我是否可以用CSS做到这一点.我真的不确定,因为我无法想象我能做些什么.

谢谢

Pee*_*Haa 18

你可以使用display: inline-block;:

http://jsfiddle.net/hLVV9/1/

虽然请查看浏览器支持,因为如果IE不支持它,我不会感到惊讶.


Gui*_*ère 8

迄今为止最好的解决方案:

pre {
    white-space: pre-wrap;
}
Run Code Online (Sandbox Code Playgroud)