自动换行强制元素达到最大宽度

发布于 2024-10-07 08:07:28 字数 989 浏览 0 评论 0原文

我有以下标记(嗯,真实标记的重现案例):

<!DOCTYPE html>
<html>
<head>
    <title>Wrapping Woes</title>
    <style>
      .button {
        border: 1px solid black;
        background: #CCFFCC;
        min-width: 40px;
        max-width: 80px;
        height: 80px;
        display: inline-block;
        text-align: center;
        vertical-align: top;
      }
      .button:hover {
        background: #CCCCFF;
      }
    </style>
  </head>
  <body>          
    <span class="button">
      Lorem Ipsum
    </span>
    <span class="button">
      Dolor
    </span>   
    <span class="button">
      Set Amet
    </span>  
</body>
</html>

按钮内容已生成且未知。我的问题主要在于“Lorem Ipsum”按钮 - 尽管它可以换行,但它仍然占据了完整的最大宽度(80px),而理想情况下我希望它缩小到单词的宽度。这实际上是 IE7 标准模式下的行为,但在 IE8 模式或任何符合标准的浏览器中似乎并非如此。

我尝试了 width: 1px; 但这也会导致“Set Amet”换行。

如何使元素宽度取决于换行文本,而不是预换行文本?

I have the following markup (well, a repro case for the real markup):

<!DOCTYPE html>
<html>
<head>
    <title>Wrapping Woes</title>
    <style>
      .button {
        border: 1px solid black;
        background: #CCFFCC;
        min-width: 40px;
        max-width: 80px;
        height: 80px;
        display: inline-block;
        text-align: center;
        vertical-align: top;
      }
      .button:hover {
        background: #CCCCFF;
      }
    </style>
  </head>
  <body>          
    <span class="button">
      Lorem Ipsum
    </span>
    <span class="button">
      Dolor
    </span>   
    <span class="button">
      Set Amet
    </span>  
</body>
</html>

The button contents are generated and unknown. My problem is primarily with the "Lorem Ipsum" button - despite it wrapping, it is still taking up the full max-width (80px), when ideally I'd like it to shrink down to the width of the word. This is actually the behaviour in IE7 Standards Mode, but it seems not so in IE8 mode or any standards compliant browser.

I tried width: 1px; but that causes the "Set Amet" to wrap as well.

How can I make the element width dependant on the wrapped text, not the pre-wrapped text?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2024-10-14 08:07:28

我最终做了一些服务器端包装。无论如何,我只想最多换行 2 行,因此在标记中手动放置换行符会产生所需的结果。似乎仅在 css 中不可能。

基本上,如果文本超过 12 个字符,我会用新行替换最中间的空格。虽然不完美,但效果已经足够好了。

I ended up doing some server-side wrapping. I only wanted wrapping to a maximum of 2 lines anyway, so manually putting a line break in the mark up produced the results required. Doesn't seem possible in css only.

Basically, I replaced the middle-most space with a new line if the text was more than 12 characters. Not perfect, but it works well enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文