【发布时间】:2021-03-23 15:33:51
【问题描述】:
我需要装饰一些非常大的多行标题,并在它们上方加粗边框。 边框应始终与文本块中最长的行一样长,但不能超过此长度。 这是一张图片来说明它应该是什么样子:
我发现了一大堆解决类似问题的问题,但没有一个完全适合我的问题。
到目前为止,我已经尝试了不同的方法,可以在下面的小提琴中找到。
- 将标题设置为
inline-block并添加一个顶部边框或:before 元素,这非常适合单行标题,但是一旦文本换行,inline-block 元素就会扩展为100% 宽度和边框结束太长了。 (对应小提琴中的黄色和红色边框) - 将文本包装在跨度中,设置跨度相对并尝试绝对定位边框。当最后一行文本最长时,这很有效,但是当最后一行比之前的短时,边框最终会太短。 (对应小提琴中的蓝色边框)
- 在内联元素上添加border-top,这当然会导致所有文本行都有边框。
:first-line伪类之类的东西在这里可能会有所帮助,但我找不到类似的东西。
我还尝试摆弄设置 display: inline-block; 和设置 width: max-content 或 width: fit-content,但这些仅在我手动添加换行符时才对我的问题有效,而不是在文本自行换行时。
https://jsfiddle.net/rj8k2tmg/56/
body {
width: 700px;
}
h1 {
font-family: sans-serif;
margin-top: 0.75em;
position: relative;
max-width: max-content;
text-transform: uppercase;
}
.headline:before {
content: '';
display: block;
position: relative;
top: 0;
left: 0;
right: 0;
border: 0;
border-top: 4px solid red;
}
.headline__wrapper {
display: inline;
position: relative;
}
.headline__wrapper:before {
content: '';
display: block;
position: absolute;
bottom: 100%;
left: 0;
right: 0;
border: 0;
border-top: 4px solid blue;
}
.headline__inline-border {
border-top: 4px solid green;
}
<p>Before Element on headline, doesn't fit when text wraps</p>
<h1 class="headline">
Short headline
</h1>
<h1 class="headline">Long headline that wraps, first line shorter than the 2nd</h1>
<h1 class="headline">Long headline that wraps, the 2nd line should be shorter.</h1>
<hr>
<p>Works fine for cases 1 and 2, but not for case 3 where the second line is shorter.</p>
<h1 class="headliner__w-wrapper">
<span class="headline__wrapper">
Short headline
</span>
</h1>
<h1 class="headliner__w-wrapper">
<span class="headline__wrapper">
Long headline that wraps, first line shorter than the 2nd
</span>
</h1>
<h1 class="headliner__w-wrapper">
<span class="headline__wrapper">
Long headline that wraps, the 2nd line should be shorter.
</span>
</h1>
<hr>
<p>Border-top on inline-wrapper / Adds border on all lines</p>
<h1 class="headliner__w-wrapper">
<span class="headline__inline-border">
Short headline
</span>
</h1>
<h1 class="headliner__w-wrapper">
<span class="headline__inline-border">
Long headline that wraps, first line shorter than the 2nd
</span>
</h1>
<h1 class="headliner__w-wrapper">
<span class="headline__inline-border">
Long headline that wraps, the 2nd line should be shorter.
</span>
</h1>
【问题讨论】:
-
到 jsfiddle 的链接必须附有问题本身的代码,但这对于 css 是不可能的 - 一旦元素换行,它就是 100% 宽度
-
对不起,我马上补充
-
@FabrizioCalderanlovestrees 据我所知,一旦文本换行,它就会扩展到 100%。这正是我的问题所在。如果您确实知道如何防止帽子,请告诉我。
-
如前所述,这在 CSS 中是不可能的
-
如前所述,这在 CSS 中是不可能的