How to center pseudo-element?

please consider the following code:

.pseudo:after {
content: "hello";
display: block;

<p class="pseudo">some content, not too long</p>

Is there a way to center that pseudo element in regards to the width of <p>? The pseudo element should appeared centered under the text displayed in <p>.

I tried with position absolute, with a negative value for bottom (so far so good), but I can’t get things to get centered.


-jj. :slight_smile:

I have to rush off now, but couldn’t resits a quick experiment. No doubt better ways, but …

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<style media="all">
.pseudo {display: table;}
.pseudo:after {
content: "hello";
display: block;
text-align: center;

<p class="pseudo">some content, not too long</p>


display: inline-block does the trick as well.

Is there a way to center that pseudo element in regards to the width of <p>?

Sure, just give it text-align: center;

What you’re really asking is how to make the p the width of it’s text.

Yeah, I was going to suggest that, although it seemed to move the paragraph down a bit, so display: table seemed preferable here. (I probably should investigate why inline-block made the para jump down a bit, but I’m too lazy. :smiley: )

It’s the top margin on the p element causing the difference as the table (display:table) collapses the margin but inline-block does not (because it creates a new block formatting context). If you set p margin:0 then both routines work the same or if you set html,body to margin:0 then they both behave the same.

Thanks Paul. :slight_smile: I wonder if setting the p to display: inline-block or :table will cause layout issues. I guess only jjshell can tell us that.

Yes it depends on the context. It may be that the p element didn’t need to shrink to fit so could remain block.