实现横向链接列表完整换行:避免单词断行与溢出
Hey there! Let's tackle that frustrating word-wrapping and overflow issue you're facing with your sidebar sub-category links. The problem happens because browsers default to breaking words mid-character to fit available space, which leads to messy line breaks or content spilling outside the container. Here's how to fix it:
Step-by-Step Solution
We need to adjust two key parts of your CSS: the container for each link item, and the link text itself, to enforce whole-word wrapping and contain overflow.
Updated SCSS Code
.sidebar-widget { position: relative; z-index: 1; background-color: #eff4f9; padding: 60px 25px; margin-bottom: 40px; h3 { font-size: 30px; margin-bottom: 30px; font-weight: 400; color: $primary-color; @media #{$breakpoint-xs} { font-size: 24px; } } .sub-category-item { border: 2px solid black; border-radius: 5px; display: inline-block; // 让分类项横向排列且能正确包裹内容 margin-right: 20px; margin-bottom: 10px; // 换行后增加间距,避免拥挤 padding: 0 5px; // 防止文字紧贴边框 a { font-weight: 700; color: $secondary-color; padding: 2px; white-space: normal; // 允许文本正常换行 word-break: keep-all; // 禁止单词内部断行 overflow-wrap: anywhere; // 空间不足时整词自动换行 display: inline-block; // 继承容器的换行规则 } } }
Key CSS Property Breakdown
display: inline-blockon.sub-category-item: This keeps each category item side-by-side horizontally, while ensuring the container properly wraps the link text to prevent overflow.word-break: keep-all: Guarantees browsers never split individual words mid-character (so "Mind and Soul" won't get chopped into "Mind and So" + "ul").overflow-wrap: anywhere: When a full word or phrase can't fit on the current line, this forces the entire block to move to the next line instead of spilling outside the widget.margin-bottom: 10px: A small quality-of-life tweak to add spacing between wrapped items for better readability.
HTML Works As-Is
Your existing HTML doesn't need any changes—just add more sub-category items as needed, and the CSS will handle the rest:
<div className="sidebar-widget"> <h3>Sub Categories</h3> <span className="sub-category-item"> <a href="#"> Random words </a> </span> <span className="sub-category-item"> <a href="#">Mind and Soul</a> </span> <span className="sub-category-item"> <a href="#">Must Go Places</a> </span> </div>
With these updates, your links will wrap cleanly at whole-word boundaries, and long phrases will stay contained within the sidebar widget no matter the screen size. Resize your browser to test it out—everything should behave exactly as you want!
内容的提问来源于stack exchange,提问作者Muljayan

