我试图找到一种在CSS中创建自定义高亮的方法,该高亮占据文字高度的约50%,在垂直方向上居中,并且可以适用于多行文本。我可以通过几种方式实现单行文本的效果,但是当应用于多行文本时,所有方式都失败了或无法垂直居中。
hr {
margin: 15px 0;
}
.title-psuedo .background {
position: relative;
padding-left: 40px;
padding-right: 40px;
}
.title-psuedo .background:after {
content: "";
position: absolute;
width: 100%;
background: yellow;
left: 0;
bottom: 0.3em;
height: 0.4em;
z-index: -1;
}
.title-mark mark {
display: inline-block;
line-height: 0em;
padding-bottom: 0.5em;
padding-left: 40px;
padding-right: 40px;
}
.title-shadow .background {
box-shadow: inset 0 -0.5em 0 yellow;
padding-left: 40px;
padding-right: 40px;
}
.title-background .background {
padding: 0 40px;
line-height: 0.5em;
margin: 0.25em 0;
background-color: yellow;
display: inline-block;
}
<div class="title title-psuedo">
<span class="background">This is the desired effect.</span>
</div>
<hr>
<div class="title title-psuedo">
<span class="background">This works on one line, but not when the text spans onto 2 separate lines, as the background messes up and only appears on the last line of the content.</span>
</div>
<hr>
<div class="title title-mark">
<mark>This works on one line, but not when the text spans onto 2 separate lines, as the lines merge into one single line which isn't legible. Also, I'm not sure the highlight can be centered vertically.</mark>
</div>
<hr>
<div class="title title-shadow">
<span class="background">This works on multiple lines, but I'm not sure the highlight can be centered vertically. Additionally, the second line does not have the same padding as the first.</span>
</div>
<hr>
<div class="title title-background">
<span class="background">This works on one line, but not when the text spans onto 2 separate lines as the line height collapses the text together and the highlight covers both lines without a gap. The second line does have the initial padding however.</span>
</div>