将包含元素的文本力包装到max-width [英] Wrapping text forces containing element to max-width

查看:115
本文介绍了将包含元素的文本力包装到max-width的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 div s,所有的样式都是内联块,因此在一行中彼此相邻。这些div具有140像素的 max-width ,并且包含使其宽度变化到此大小的文本。

I have several divs that are all styled as inline-blocks, and therefore sit in a row next to each other. These divs have a max-width of 140px, and contain text that cause them to vary in width up to that size.

示例标记:

<div class="block">A single line</div>
<div class="block">Two distinctively different lines</div>
<div class="block">A somewhat egregious demonstrative amount of text</div>

样式示例:

.block {
    display: inline-block;
    vertical-align: top;
    max-width: 140px;
    background-color: lightgrey;
    text-align: center;
}

如这个小提示所示,比 max-width 属性更宽的文本会如你所期望的那样被覆盖。问题是,它似乎也强制其容器 div 留在 max-width ,即使包装文本在技术上不需要太多的空间。

As demonstrated in this fiddle, text that is wider than the max-width property wraps, as you would expect. The problem is that it also seems to force its container div to stay at the max-width, even though the wrapped text doesn't technically require that much space.

有一个跨浏览器,只有HTML / CSS的方式,将这些块shink-wrap到最小的宽度一旦文本换行?我知道我可以强制它与适当放置< br> s,但这些块应该包含用户输入的文本。

Is there a cross-browser, HTML/CSS-only way to "shink-wrap" these blocks to their smallest width once the text wraps? I'm aware that I can force it with appropriately placed <br>s, but these blocks are supposed to contain user-entered text.

推荐答案

代替 max-width:140px ,请考虑 width:min-content

Instead of max-width: 140px, consider width: min-content.

CSS

.block {
    display: inline-block;
    vertical-align: top;
    /* max-width: 140px; */
    background-color: lightgrey;
    text-align: center;

    /* new */
    width: min-content;
    padding: 0 5px; 
}

DEMO: https://jsfiddle.net/ex4n8m49/2/

注意: c $ c> min-content 检查前缀要求浏览器支持

Note: Before implementing min-content check prefixing requirements and browser support.

我不确定有没有CSS解决方案,正在请求。如果您决定尝试使用JavaScript,以下帖子的接受答案可能会帮助您:

I'm not sure there's a CSS only solution, as you are requesting. In case you decide to try JavaScript, the accepted answer to the following post may help you:

这篇关于将包含元素的文本力包装到max-width的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆