现代CSS能确定一行文本是否换行吗?

avwztpqn  于 2023-02-26  发布在  其他
关注(0)|答案(2)|浏览(300)

假设我有这样的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方法来检测文本是否换行?

fnvucqvd

fnvucqvd1#

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

我也想不出一种没有JavaScript的方法来做这件事,而不出现一些暂时的丑陋:
要检查一个block元素是否会使用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是自顶向下的,您可能还需要检查计算的样式Map,以便执行一些不同的操作(也可能不需要)。
如果你(或者其他阅读这篇文章的人)实际上并不关心它是否会换行,实际上只是想要基于视口宽度之类的东西的不同样式,请查看CSS' media queries feature
如果您希望在所讨论的元素大小发生变化时获得更新,则需要使用the ResizeObserver API

agxfikkp

agxfikkp2#

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

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

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

相关问题