如何防止文本溢出其父元素并导致换行

74 阅读1分钟

若要防止文本溢出其父元素并导致换行符,可以使用 CSS overflow-wrap属性。此属性允许您指定浏览器可以将目标元素内的一行文本分成多行,否则无法在某个位置。以下是使用它的方法:

.example {
  overflow-wrap: break-word;
}

 

该属性有三个可能的值:

  • normal:这是默认值。浏览器将根据正常的换行规则换行。单词或未中断的字符串不会中断,即使它们溢出容器。
  • break-word:此值允许太大而无法放入其容器的单词或字符串在任意位置换行以强制换行。即使使用了连字符属性,也不会插入连字符。
  • anywhere:此值在任何时候(甚至在单词内)中断单词或字符串。这在处理可能破坏网页布局的长 URL 或其他不间断的文本字符串时很有用。

可以将该属性应用于父元素,以防止文本溢出并导致换行符。下面是一个示例:overflow-wrap

.postedIn {
  overflow-wrap: break-word;
}

 
<div class="col-8 mt-3 postedIn">
  <span id="postedIn">Posted in:</span>&nbsp;<?php the_category('&nbsp;') ?>
  &nbsp;<a href="http://localhost/wordpress/archives/category/test-1" rel="category    tag">Test 1</a>
  &nbsp;<a href="http://localhost/wordpress/archives/category/test-2" rel="category tag">Test 2</a>
  &nbsp;<a href="http://localhost/wordpress/archives/category/test-4" rel="category tag">Test 4</a>
  &nbsp;<a href="http://localhost/wordpress/archives/category/test-5" rel="category tag">Test 5</a>
  &nbsp;<a href="http://localhost/wordpress/archives/category/test3" rel="category tag">Test 3</a>
  &nbsp;<a href="http://localhost/wordpress/archives/category/uncategorized" rel="category tag">Uncategorized</a>    
</div>

 

请注意,除 IE、Opera Mini 和 Edge 之外的所有主要浏览器都支持该overflow-wrap属性。如果需要支持这些浏览器,可以使用该word-wrap属性作为替代属性,它具有类似的功能。