【问题标题】:Can modern CSS determine whether a line of text is wrapped?现代 CSS 能判断一行文字是否换行吗?
【发布时间】:2023-02-25 14:49:05
【问题描述】:

假设我有一些这样的 HTML:

<h1>The is a very long title, on small screens it will wrap but not on wider screens</h1>

我想在非常大的屏幕上将 text-align 属性设置为 center,在较小的屏幕上设置为 left。是否有任何纯 CSS 方法来检测文本是否换行?

【问题讨论】:

  • 您是否想要一个完全通用的解决方案 - 即问题是否可以表述为“如果文本适合一行,那么它应该在屏幕上居中,如果它需要换行,那么它必须保持对齐”?
  • 是的,类似的东西。你是对的。

标签: css


【解决方案1】:

据我所知(我很可能是错的),不。您无法检测一行是否会单独使用 CSS 换行。

我想不出一种没有 JavaScript 的方法来做到这一点,同时也没有一些暂时的丑陋闪光:

要检查块元素是否会用 JavaScript 换行,您可以这样做,它基本上暂时强制元素没有文本换行,然后检查其计算/呈现的大小并将其与父元素的宽度进行比较(并根据父元素对文本流动和调整大小进行一些其他检查:

function checkWillOverflow(elem) {
  const parent = elem.parentElement;
  const parentStyleMap = parent.getComputedStyleMap();
  if (parentStyleMap.get("width").value === "max-content") {
    return false;
  }
  if (parentStyleMap.get("overflow-x").value === "scroll") {
    return ; // TODO: you need to decide what you want to happen here.
  }

  // this function assumes there is nothing in the style attributes to overwrite
  // (and that anything it takes higher precedence over is in style rules).
  // if there is, you will need to "back up" those values and restore them after.
  elem.style.width = "max-content";
  // set border and padding of parent to empty in preparation to get the
  // calculated width of the content box only.
  parent.style.borderWidth = "0";
  parent.style.padding = "0";

  const willOverflow = elem.getBoundingClientRect().width > parent.getBoundingClientRect().width;

  // undo the style attribute changes
  parent.style.removeProperty("border-width");
  parent.style.removeProperty("padding");

  return willOverflow;
}

如果 writing-mode 是自上而下的(或者您可能不是),您可能还想检查计算样式映射以执行不同的操作。

如果您(或阅读本文的其他人)实际上并不关心它是否会换行,而实际上只是想要基于视口宽度等因素的不同样式,请查看CSS' media queries feature

如果您想了解有关元素大小更改的最新信息,您需要使用the ResizeObserver API

【讨论】:

    【解决方案2】:

    您可以使用媒体查询根据屏幕大小为元素设置不同的 CSS。

    @media (min-width: 30em) {
      /* … */
    }
    

    https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 2023-03-12
      • 2011-03-13
      • 1970-01-01
      相关资源
      最近更新 更多