简体   繁体   中英

centering a pseudo element

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?

 #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

Alternatively, without transformation:

#a:after {
  content: "Text";
  position: absolute;
  left: 0;
  display: block;
  text-align: center;
  width: 100%;
  color: red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM