0

I want to set a pseudo element of a div on the original div.

The problem is that the text of the div is centered.

Here is an example:

#a:after{
  content:"Text";
  position:absolute;
  left:0;
  color:red;
}
<div style="width:100%;text-align:center;">
  <p id="a">Text</p>
</div>

Why is the pseudo element not affected by the div style?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
nicoschuck
  • 201
  • 3
  • 13
  • Because you've positioned it using `position: absolute`, and none of its ancestors have a non-`static` `position` property; so it's positioned relative to the view-port. – David Thomas Feb 23 '17 at 15:38
  • @DavidThomas ok in undestand. but i need position absolute to overlay the two texts. – nicoschuck Feb 23 '17 at 15:41

2 Answers2

3

#a:after {
  content: "Text";
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  color: red;
}
<div style="width:100%;text-align:center;">
  <p id="a">Text</p>
</div>

Here's an explanation of the centering method: Element will not stay centered, especially when re-sizing screen

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

Alternatively, without transformation:

#a:after {
  content: "Text";
  position: absolute;
  left: 0;
  display: block;
  text-align: center;
  width: 100%;
  color: red;
}
Dmitry Sheiko
  • 2,130
  • 1
  • 25
  • 28