<pre> text wrapping when no need

时间:2018-03-22 23:21:33

标签: html css

I have a panel 'mock-up' on a webpage contained within a <div> and a <pre> tag thus:-

<div style="max-width:85ch;">
<pre style="background-color:#0D0D0D;color:Lime;">
...
</pre></div>

The maximum number of characters on any line within these tags is 80 characters, and the max-width is set to 85ch.

What could cause such text to wrap at a point which is not a line break when the web page is wide enough not to force a wrap?

Example of wrapping

FYI - it's supposed to look this this:- What it is supposed to look like

I thought maybe the failing example was due to the user setting their fonts bigger (using Ctrl++) but it still behaves perfectly when I do that, and only wraps when the size of the browser window is no longer big enough to hold it.

Supplementary question (which might have the same answer). Is there a way to stop it wrapping ever, i.e. even when the size of the web browser is not big enough to contain it?

2 个答案:

答案 0 :(得分:1)

尝试<pre>white-space: pre;或项white-space: pre-line;

的样式

答案 1 :(得分:0)

这是父母和孩子的字体之间的差异的副作用,或者是您使用的浏览器或其他一些CSS呈现pre元素的方式。有许多可能的原因,但最简单的解决方案是在max-width本身设置pre而不是在包含div上设置。

<div style="width: fit-content;">
    <pre style="background-color: #0D0D0D; color:Lime; max-width:85ch;">
        ...
    </pre>
</div>

max-width设置为基于字体的度量时,您将使用为该元素指定或继承的字体。当您检查元素时,您可能会在计算机值中找到类似以下内容的内容:

div {
    font-family: sans-serif;
}
pre {
    font-family: monospace;
}

85个字符的最大宽度表示0字符的宽度,以该元素设置的任何字体(此处为sans-serif)。由于pre的字体不同,因此其0字符的宽度不同。包含的父母太狭窄,所以孩子包裹。

如果您需要将div折叠到子项的宽度,可以将其设置为fit-content的宽度,或者根据上下文,您通常可以使用display: inline-block

如果它不是由您编写的CSS引起的,则可能类似于CSS重置或Normalize.css,它会尝试纠正浏览器在呈现{{1}大小时的变化方式通过使用奇怪且从未解释过的hack将pre设置为pre

同样,最简单的解决方案是上面提到的,在font-family: monospace, monospace元素本身上设置基于字体的最大宽度。