关于CSS:为什么这个”自动换行:断字”规则在Firefox中无法正常工作?

Why does this `word-wrap: break-word` rule not work as expected in Firefox?

当相应的规则在Chrome中有效时,为什么word-wrap: break-word CSS规则不能在Firefox中缩小元素?

此处的.form-field容器的宽度限制为300px,其中的legend宽度为100%。里面的长字将legend伸出来,溢出了300px的宽度。

当我使用(非标准)WebKit word-break定义将CSS break-word规则应用于Chrome时,长字被打断,并且legend元素缩小到预期的300px宽度。

在Firefox中,除非我专门将legend的宽度设置为300px,否则相应的word-wrap规则不会破坏文本并缩小元素。为什么我必须这样做? Firefox为什么不进行" 300px的100%"计算并正确设置legend的大小?

如果您在Firefox上查看此代码段,则会看到legend仍然溢出了其容器的300px宽度。

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.form-field {
  border: none;
  padding: 0;
  max-width: 300px;
  margin: 0 auto 10px;
  outline: 1px solid purple;
}

.form-field legend {
  text-align: left;
  width: 100%;
  word-wrap: break-word;
  word-break: break-word;
}

.form-field input[type=text] {
    width: 100%;
    font-size: 16px;
    padding: 7px 14px;
    box-sizing: border-box;
    border: 1px solid #c8d7e1;
}
1
2
3
4
<fieldset class="form-field">
  <legend>Betweenthesetwo, InowfeltIhadtochoose. Mytwonatureshadmemoryincommonbutallotherfacultiesweremostunequallysharedbetweenthem.</legend>
  <input type="text">
</fieldset>

(在macOS Chrome 64和Firefox 57中测试)。


Firefox不支持word-breakbreak-word值。查看MDN文档,您将看到以下内容:

enter


我们需要的是

1
word-break: break-all;

更新图例的CSS

1
2
3
4
5
6
.form-field legend {
  text-align: left;
  width: 100%;
  word-wrap: break-word;
  word-break: break-all; // Modified
}