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

时间:2015-04-28 16:51:23

标签: html css dynamic absolute

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

<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。

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

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

这里的问题是.cite的宽度传递给它的孩子 但是你可以通过在

之间添加另一个元素来解决这个问题
position: absolute;
with: 400px;

默认情况下,这样的元素是不可见的,但它会捕获鼠标事件,所以你可能希望使用

来防止它
pointer-events: none;

从最内层元素,您现在可以删除positionleftbottom属性,而是添加

display: inline-block;

这是必要的,以便在文本需要多行时将框显示为块,但仍然保持最低的宽度和高度。

您可能还想在最内部元素上重新启用指针事件:

pointer-events: all;

以上所有内容都是小提琴:http://jsfiddle.net/8ebsLc6L/4/

答案 1 :(得分:0)

这是一种方法。

将文字换入span元素.citeWrap,然后指定背景颜色,边框半径等。请注意,您不再需要max-width属性。

对于.citeBox,请设置width: 400px

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

但是,如果文本短于400px,作为内联元素的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>