如何创建特定宽度<div>或支持文本换行的两行容器?
Fixing Text Wrapping/Fixed Width for Your Homepage Image Headers
Got it, let's tackle this for your homepage! You need the text above your images to either stay within a specific width or wrap cleanly into two lines—here are two reliable, easy-to-implement solutions:
Approach 1: Fixed-Width Container with Automatic Wrapping
This sets an explicit width on your text container, so longer text will wrap once it hits that limit instead of stretching out.
Updated HTML
<div class="IconWidth31Percent PlaceWhiteIcon VerticalAlign"> <!-- Add a dedicated wrapper for the text to control its width --> <div class="image-header-text"> <span style="font-size: 18pt;"><strong><a href="http://www.rosstheexplorer.com/new-zealand/franz-joesf/">Franz Joesf</a></strong></span> </div> <div></div> <img class="Thumbnail48PercentPictureSize" src="your-image-url.jpg" alt="Franz Joesf"> </div>
CSS to Add
.image-header-text { /* Set your desired fixed width (tweak this value to match your design) */ width: 120px; /* Make sure text wraps instead of staying on one line */ white-space: normal; /* Optional: Center the text above the image for better alignment */ text-align: center; } /* Bonus: If you want to cap text at exactly two lines (add ellipsis for overflow) */ .image-header-text { width: 120px; white-space: normal; text-align: center; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
Approach 2: Flexbox for Consistent Alignment & Adaptive Wrapping
If you want the entire card (text + image) to have a consistent size while letting text wrap, flexbox is a great tool—it keeps everything aligned neatly.
Updated HTML
<div class="image-card"> <div class="image-header-text"> <span style="font-size: 18pt;"><strong><a href="http://www.rosstheexplorer.com/new-zealand/franz-joesf/">Franz Joesf</a></strong></span> </div> <img class="Thumbnail48PercentPictureSize" src="your-image-url.jpg" alt="Franz Joesf"> </div>
CSS to Add
.image-card { /* Stack text and image vertically */ display: flex; flex-direction: column; align-items: center; /* Set a fixed width for the entire card */ width: 150px; /* Optional: Add spacing inside the card */ padding: 8px; } .image-header-text { /* Allow text to wrap naturally */ white-space: normal; text-align: center; /* Add space between text and image */ margin-bottom: 8px; }
Quick Tips:
- Adjust the width values (
120px,150px) to fit your layout—test different sizes until it looks right. - The
white-space: normalrule is crucial because some inherited styles might force text to stay on a single line. - The two-line ellipsis trick works on most modern browsers, perfect if you don't want text to spill beyond two lines.
内容的提问来源于stack exchange,提问作者Ross Symonds
相关产品推荐
相关产品推荐

