当我从本地文件和 Codepen 打开它时,相同的代码看起来不同。为什么会这样?

The same code looks differently when I open it from a local file and from Codepen. Why does that happen?

这是 Chris Coyier 的一支笔,在他的文章 Handling Long Words and URLs: https://codepen.io/team/css-tricks/pen/RWaNxr.

中提到
<style>
.hyphenate {
  /* Careful, this breaks the word wherever it is without a hyphen */
  overflow-wrap: break-word;
  word-wrap: break-word;

  /* Adds a hyphen where the word breaks */
  -webkit-hyphens: auto;
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  hyphens: auto;
}

/* Demo Styles */

body {
  background: #333;
  font-family: 'Open Sans', sans-serif;
}

.container {
  background: #fff;
  border-radius: 5px;
  width: 300px;
  margin: auto auto 25px;
  padding: 25px;
}
</style>

<div class="container">
  <p class="hyphenate">For more information, please visit: http://csstricks.com/thisisanonexistentandreallylongurltoaddtoanytextinfactwhyareyoustillreadingit.</p>
</div>
<div class="container">
  <p class="hyphenate">According to Wikipedia, The longest word in any of the major English language dictionary is pneumonoultramicroscopicsilicovolcanoconiosis, a word that refers to a lung disease contracted from the inhalation of very fine silica particles, specifically from a volcano; medically, it is the same as silicosis.</p>
</div>

如果您只是在浏览器中打开此 link,它在 Firefox 中的外观如下:

下面是将所有内容复制到本地 HTML 文件时的样子:

为什么看起来不一样?

CodePen 设置包含您未包含在本地副本中的额外资源。

我会说这是因为 Codepen 界面包含它自己的 browser/rendering 引擎,它的行为可能不同于您单独使用时用于查看它的浏览器(没有 codepen“中间”)

它在本地不起作用,因为没有定义语言。只需添加

lang="en-US"

它会起作用。

Hyphenation rules are language-specific. In HTML, the language is determined by the lang attribute, and browsers will hyphenate only if this attribute is present and if an appropriate hyphenation dictionary is available.

我找到了那个信息 here, while original is in this docs。另外:

The default value of lang is unknown, therefore it is recommended to always specify this attribute with the appropriate value.

如所述here

当我们在 codepen 中执行此操作时,<body></body> 前后的 HTML 标记会在 iframe 中自动生成。 正因为如此,html 会像这样呈现。

<html class="" lang="en">

在本地我们看不到 lang 属性。 因此,尝试将 lang 属性添加到 html 标记,然后您将看到更改 <html class="" lang="en">