Prevent pseudo-element from breaking a line by itself

久未见 提交于 2019-12-07 16:29:21

问题


I have a link style that adds an SVG arrow at the end of the link using &::after. The problem is that when the viewport changes size there are times when just the SVG will break a line. How can I set it up so that the SVG always breaks the line with the last word in the <a> tag?

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

Thanks for the help.


回答1:


You can add a negative margin equal to the icon size and use padding on the parent element to rectify this. This trick will enable the break when we reach the first word and logically the icon will follow.

I also removed the margin-left and made the width bigger then adjusted the backgound position to the right.

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:


You could just wrap your last word in a <span>, then set that span to have the puesdo element and set it to white-space: nowrap;

Like this:

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


来源:https://stackoverflow.com/questions/54557236/prevent-pseudo-element-from-breaking-a-line-by-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!