Home > Software design >  Keep pseudo element on same line as parent <a> tag
Keep pseudo element on same line as parent <a> tag

Time:12-01

I have this link:

<a href="#">Laboris chuck pastrami ribeye nisi</a>

I'm adding an arrow using a pseudo element:

a::after {
    content: ">";
    margin-left: 7px;
    display: inline-block;
}

But how can I prevent the pseuto element to break into a new line alone? I want to keep the arrow attached to the last word at all times. See Fiddle. If I remove display: inline-block; from the ::after, it seems to work and the arrow breaks with the last word, but then the pseudo element is also underlined like the parent. I don't want that.

How can I get around this? Any ideas?

What I have

What I want

CodePudding user response:

it's happening because of your width in your "box" div. remove the width and it'll work just like the below:

[ edited accordingly as per question's edit]

span::after {
    content: ">";
    margin-left: 7px;
    display: inline-block;
}

span{
  display: inline-block;
  text-decoration: underline;
}

.box {
  width: 225px;
}
<div >
  <a href="#">Laboris chuck pastrami ribeye <span>nisi</span></a>
</div>

CodePudding user response:

Your .box has a fixed width therefore your :after content is forced to wrap. You can prevent this by setting its position as absolute;

a::after {
content: ">";
margin-left: 7px;
display: inline-block;
position:absolute; /* <-- position it absolutely */
}

.box {
  width: 225px;
  border:1px dotted red; /* <-- added to illustrate my point */
}
<div >
  <a href="#">Laboris chuck pastrami ribeye nisi</a>
</div>

EDIT

Further to your clarification. If your :after is inline it is rendered the same as if you had just appended > at the end of the link (ie without using a pseudo element). This is why it is positioned as you expect when your remove display:inline-block and is the reason why it also gets the underline. What you want cannot be done with the code you have. You would need to add some more mark-up to differentiate the bits you do want underlined from that which you do not. For example, by wrapping the bit you want underlined in a span:

a {text-decoration:none;}
a>span {text-decoration:underline;}

a::after {
content: ">";
margin-left: 7px;
display: inline;
}

.box {
  width: 225px;
  border:1px dotted red; /* <-- added to illustrate my point */
}
<div >
  <a href="#"><span>Laboris chuck pastrami ribeye nisi</span></a>
</div>

  •  Tags:  
  • css
  • Related