首页 > 解决方案 > DIV is not as wide as the page in Chrome (mobile) when a long word overflows

问题描述

Case 1: Without initial-scale=1.0

Here is the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Foo</title>
    <meta name="viewport" content="width=device-width">
    <style>
      body {
        margin: 0;
      }
      .header {
        background: green;
        color: white;
        height: 2em;
      }
    </style>
  </head>
  <body>
    <div class="header">
      Header
    </div>
    <p>
      Veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongword
    </p>
</html>

I open this page with Chrome on a desktop browser. Then I right click the page and select Inspect. Then I click the mobile icon in the inspector and select Galaxy S5 from the dropdown. I see this:

The same result is reproducible with Chrome on actual mobile phone. The <div> element is not as wide as the page.

Case 2: With initial-scale=1.0

Here is the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Foo</title>
    <meta name="viewport" content="width=device-width; initial-scale=1.0">
    <style>
      body {
        margin: 0;
      }
      .header {
        background: green;
        color: white;
        height: 2em;
      }
    </style>
  </head>
  <body>
    <div class="header">
      Header
    </div>
    <p>
      Veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongword
    </p>
</html>

Here is the output now. The page seems okay when it loads but as we scroll right, we see that the <div> is still not as wide as the entire width of the page.

Output in both cases remain the same even if I add width: 50% to the .header in the CSS.

Question

Why does this issue occur? How can I fix it such that the <div> element is really as wide as the page and the entire long word is visible to the right (it is okay if the user has to scroll right to see the long word)?

标签: htmlcssgoogle-chromemobile

解决方案


你在这里处理溢出;文本所在的元素不会扩展其宽度 - 因此继承此宽度的子元素也不会变宽。

解决方案(或解决方法,取决于您希望如何查看)是强制中断这么长的单词,https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap

如果您检查该页面下方的浏览器兼容性表,您会看到该值anywhere尚不支持浏览器,预计 Firefox 65+ - 但在大多数情况下,break-word应该支持。

(您还可以查看类似的属性https://developer.mozilla.org/en-US/docs/Web/CSS/word-break有时两者的结合可以在旧浏览器中产生更好的结果。)


推荐阅读