我基本上有一个包含两个 block 的容器:一个 block 将具有动态宽度(基于其中的文本),另一个 block 的宽度应与动态宽度相同。如果第二个 block 的宽度比里面的文本大,它必须打断文本以保持与第一个 block 相同的宽度。
<container>
<fixed_dynamic>
Lorem ipsum dolor sit amet
</fixed_dynamic>
<samedynamic>
few words
</samedynamic>
</container>
我可以通过这种方式取得一些成就:https://jsfiddle.net/prxus5vm
问题是,如果我尝试在第二个宽度中写一些东西,使 div 拉伸(stretch),它不会破坏单词:https://jsfiddle.net/prxus5vm/1/ .它应该打破单词并保持第一个 block 的宽度。
有什么解决办法吗?我正在寻找 CSS 解决方案,希望尽可能避免使用 javascript。
最佳答案
如果您尝试使用 table-layout
属性尽可能地缩小父级,则您缺少设置的小 width
。
完成此操作后,第一个元素可以是文本 block 或图像。最后,white-space:nowrap
可以派上用场,以避免文本换行并设置您要查找的宽度。
div {
display: inline-table;/*NEEDED inline for demo it is still using the table-layout */
width: 1%; /*NEDEED or 0 , see it alike a min-width */
margin:5px /* not needed here */
}
div * {
padding: 0.25em ; /* not needed here */
margin: 0; /* not needed here */
}
div h1 {
background: green; /* not needed here */
white-space: nowrap; /* NEDEED */
font-size:1.1rem /* not needed here */
}
p {
background: yellow; /* not needed here */
}
<div>
<h1>
Lorem ipsum dolor sit amet
</h1>
<p>
more words than fixed dynamic block
</p>
</div>
<div>
<h1>
A shorter text
</h1>
<p>
more words than fixed from dynamic block
</p>
<p>
and a few more words
</p>
</div>
<h1>BUT, there is a disclaimer !</h1>
<div>
<h1>
short
</h1>
<p>
here are words that are themselves longer than the reference ....
</p>
</div>
关于html - 两个 block : one with dynamic width, 一个宽度相同 动态一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55289443/