49

这张图片显示了我在代码中发生的事情 这是我的博客页面。有时我不得不在博客中使用 C#、PHP 和其他代码片段。因此,我使用 pre 标签使它看起来不错,并保持格式代码不变。pre标签宽度为 100%,并且有背景颜色。但是,文本离开了它,如上图所示,水平滚动条将出现。我该如何克服呢?我不想要底部滚动条。

4

5 回答 5

87

There are a few solutions:

The simplest is to place line breaks in the text. This probably is not what you want though, since it will either leave large right margins or still cause scroll bars, unless the browser window is just the right size.

Another is to use white-space:pre-wrap; in the CSS for your <pre> tag. This will cause the text to wrap to a new line as necessary, but still preserve all whitespace present in the source. See https://developer.mozilla.org/en-US/docs/Web/CSS/white-space for more information about this CSS property.

Alternatively, if you do not want any line breaks added (either manually or through automatic word wrap), you can use one of the following CSS properties for your <pre> tag:

  • overflow-x:hidden; This will simply cut off the text that extends past the right edge. It will not be visible at all.
  • overflow-x:scroll; This will cause scroll bars to appear within your webpage in case text extends past the right edge. This will prevent the entire page from getting so wide that scroll bars appear at the bottom. See http://www.w3schools.com/cssref/playit.asp?filename=playcss_overflow-x&preval=scroll for an example.
  • overflow-x:auto; Like overflow-x:scroll; except the scrollbars only appear if required. (Thanks ccalvert in the comments)
于 2012-12-03T03:38:47.570 回答
9

添加样式:

pre { 
    white-space: pre-wrap; 
    word-break: break-word;
}
于 2018-09-06T07:54:08.167 回答
3

我的行包含在<a>标签中。这对我有用:

a, pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
于 2019-10-14T07:22:28.257 回答
2

您可以使用一些 CSS 属性:

pre {
display: flex;
white-space: normal;
word-break: break-word;
}

可选地,如果<pre>在里面<span>

span pre { display: inline-flex; }
于 2016-07-10T00:10:57.150 回答
1

您可以添加一个包装器 div 并添加下一个 CSS 属性

{
   div#wrapper {
      overflow: scroll;
      display: grid;
   }
}
于 2022-02-02T12:41:49.540 回答