【问题标题】:Prevent pseudo-element from breaking a line by itself防止伪元素自行断行
【发布时间】:2019-02-06 15:36:31
【问题描述】:
我有一个链接样式,它使用&::after 在链接末尾添加一个 SVG 箭头。问题是当视口改变大小时,有时只有 SVG 会换行。我该如何设置它,以便 SVG 总是与 <a> 标记中的最后一个单词换行?
.txtbtn {
font-size: 1.125rem;
line-height: 1.222222222;
letter-spacing: 2.57px;
color: orange;
text-decoration: none;
position: relative;
text-transform: uppercase;
}
.txtbtn::after {
position: relative;
top: 0;
display: inline-block;
margin-left: 12px;
width: 22px;
height: 15px;
content: "";
background: url('https://www.jea.com/cdn/images/svgs/right-arrow.svg') no-repeat center center;
background-size: contain;
}
<p><a href="#" class="txtbtn">Lorem ipsum dolor sit amet, consectetur abittor.</a></p>
感谢您的帮助。
【问题讨论】:
标签:
css
line-breaks
pseudo-element
【解决方案1】:
您可以添加一个等于图标大小的负边距,并在父元素上使用填充来纠正此问题。这个技巧将在我们到达第一个单词时启用中断,并且逻辑上图标将跟随。
我还去掉了margin-left,把宽度变大了,然后把背景位置调整到了右边。
p {
padding-right:22px;
}
.txtbtn {
font-size: 1.125rem;
line-height: 1.222222222;
letter-spacing: 2.57px;
color: orange;
text-decoration: none;
position: relative;
text-transform: uppercase;
}
.txtbtn::after {
position: relative;
top: 0;
display: inline-block;
margin-right:-32px;
width: 32px;
height: 15px;
content: "";
background: url('https://www.jea.com/cdn/images/svgs/right-arrow.svg') no-repeat right/contain;
}
<p><a href="#" class="txtbtn">Lorem ipsum dolor sit amet, consectetur abittor.</a></p>
【解决方案2】:
您可以将您的最后一个单词包装在 <span> 中,然后将该范围设置为具有 puesdo 元素并将其设置为 white-space: nowrap;
像这样:
.txtbtn {
font-size: 1.125rem;
line-height: 1.222222222;
letter-spacing: 2.57px;
color: orange;
text-decoration: none;
position: relative;
text-transform: uppercase;
}
.txtbtn span::after {
position: relative;
top: 0;
display: inline-block;
margin-left: 12px;
width: 22px;
height: 15px;
content: "";
background: url('https://www.jea.com/cdn/images/svgs/right-arrow.svg') no-repeat center center;
background-size: contain;
}
.txtbtn span {
white-space: nowrap;
}
<p><a href="#" class="txtbtn">Lorem ipsum dolor sit amet, consectetur <span>abittor.</span></a></p>