问题描述
我正在尝试通过CSS模拟这种效果:
I'm trying to emulate this effect via CSS:
这是一个问题,是因为它需要可重复使用.红色下划线的大小应由文本长度决定,但也应以可预见的方式溢出其容器,例如:
The reason this is an issue is because it needs to be re-usable. The red underline's size should be dictated by the text length, but also overflow its container in a predictable manner, e.g.:
<div>
<h1>This</h1>
<h1>Cool</h1>
<h1>Effect</h1>
</div>
红色下划线应在div之外向左延伸10px,然后在文本本身上向右溢出约50px.因此,总的来说,红线比文本本身宽60像素.
The red underline should extend outside the div by 10px on the left, and then also overflow the text itself by roughly 50px on the right. So, all told, the red line is +60 pixels wider than the text itself.
如何在没有每次手动操作的情况下实现此效果?我在伪元素方面还没有成功,框阴影也不会在需要时左右扩展.
How can I achieve this effect without doing it manually each time? I've had no success with pseudo elements, and box-shadow won't extend on the left and right as I need it to.
推荐答案
伪元素是我的答案.在:after元素上设置z-index使其位于父元素后面是一个巧妙的技巧.这些元素不能是块元素,但除此之外,它似乎很简单.
Pseudo elements was the answer for me. Setting z-index on the :after element to get it positioned behind the parent element is a neat trick. The elements can't be block elements, but other than that it seemed straightforward.
html {
min-height: 100%;
}
body {
min-height: 100%;
background: linear-gradient(to bottom, #0b122f 0%, #17457d 100%);
padding: 20px;
}
h1 {
position: relative;
display: inline-block;
color: #fff;
font-family: sans-serif;
font-size: 100px;
font-weight: 300;
margin: 0;
}
h1:before {
content: "";
background: red;
height: .25em;
width: calc( 100% + 60px);
position: absolute;
bottom: .15em;
left: -10px;
z-index: -1;
}
<div>
<h1>This</h1>
<br />
<h1>Cool</h1>
<br />
<h1>Effect</h1>
</div>
这篇关于响应文本长度时,下划线溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!