centering a pseudo element

帅比萌擦擦* 提交于 2019-12-12 03:49:11

问题


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?


回答1:


#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




回答2:


Alternatively, without transformation:

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


来源:https://stackoverflow.com/questions/42420062/centering-a-pseudo-element

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