绝对容器中的最大宽度段落

Max-Width Paragraph in Absolute Container

我希望绝对定位元素内的段落以指定的最大宽度分隔文本,但如果内容较小,则不填充整个 space。

<p>Text
<span class="cite">Reference
    <span class="citeBox">A long sentence that needs to have a line break.</span>
</span>.
Text
<span class="cite">Reference
    <span class="citeBox">Short</span>
</span>
Text.
</p>

.cite {
    position: relative;
}
.cite .citeBox {
    position: absolute;
    max-width: 400px;
    left: 0;
    /*...*/
}

http://jsfiddle.net/8ebsLc6L/1/

也就是说,Short-Box 应该很小,而 Big-Box 应该在 400px 处断开。所有框都需要随参考跨度动态移动。

当前代码没有将 Big-Box 扩展到 400px。

解决方案应该不需要 Javascript。

非常感谢您的帮助!

这是一种方法。

将文本包裹在 span 元素中,.citeWrap 并指定背景颜色、边框半径等。请注意,您不再需要 max-width 属性。

对于.citeBox,设置width: 400px

会发生的是.citeWrap将使用400px作为工作宽度来布局文本,行框将不超过400px。

但是,如果文本短于 400 像素,作为内联元素的 span 将具有收缩以适合宽度,因此您将获得刚好覆盖文本的背景颜色。

.cite {
    position: relative;
    color: blue;
}
.cite .citeBox {
    position: absolute;
    width: 400px;
    left: 0;
    bottom: 20px;
}
.cite .citeWrap {
    padding: 5px 15px;
    background-color: rgba(0, 0, 0, .6);
    border-radius: 5px;
    color: #fff;
    font-size: 1.2rem;
    display: inline-block;
}
p {
  margin-top: 4.0em; /* for demo only */
)
<p>To visualize an algorithm, we don’t merely fit data to a chart; there is no primary dataset. Instead there are logical rules that describe behavior. This may be why algorithm visualizations are so unusual, as designers experiment with novel forms to better communicate. Here is Brets wonderful 
    <span class="cite">Reference<span class="citeBox"><span class="citeWrap">A long sentence that needs to have a line break. Make it a bit longer and you see multiple lines.</span></span></span>. 
To visualize an algorithm, we don’t merely fit data to a chart; there is no primary dataset. Instead there are logical rules that describe behavior. This may be why algorithm visualizations are so unusual, as designers experiment with 
    <span class="cite">Reference<span class="citeBox"><span class="citeWrap">Short</span></span></span>
 novel forms to better communicate. Here is Brets.</p>

我相信只修改 CSS.
是不可能达到你想要的效果的 但是,我想我通过添加另一个 <span> 元素来管理它。

这里的问题是 .cite 的宽度传递给它的 children。
但是你可以通过在它们之间添加另一个元素来解决这个问题

position: absolute;
with: 400px;

这样的元素在默认情况下是不可见的,但它会捕获鼠标事件,因此您可能想要阻止它,使用

pointer-events: none;

从最里面的元素开始,您现在可以删除 positionleftbottom 属性,而是添加

display: inline-block;

这是必要的,以便在文本需要多行的情况下将框显示为一个块,但仍然保持尽可能低的宽度和高度。

您可能还想 re-enable 最内部元素上的指针事件:

pointer-events: all;

以上全部打包成一个fiddle:http://jsfiddle.net/8ebsLc6L/4/