Using the :after CSS pseudo-element without inserting content

依然范特西╮ 提交于 2019-12-08 17:34:13

问题


Is it possible to use the :after CSS pseudo-element to offset alignment without actually inserting anything in content: "". It doesn't seem to render unless content is specified so just wondered whether this is possible or if there are any known workarounds.

As an example:-

.nav-primary li.level0 a:after {
    content: "";
    padding-right: 1px;
    margin-left: -1px;
}

As you can see from the example, simply changing the colour of the content would not work in this instance as would still consume space affecting the offset.


回答1:


It is possible to use an :after pseudo-element with the content property set to the empty string "", but not without setting it all (so that it has its initial value none, which means that the pseudo-element is not generated at all).

The reason why you do not see any effect is that your settings effectively cancel each other out. You set a negative left margin, shifting the element leftwards, but you set an equal amount of padding. The pseudo-element itself is empty and thus invisible, so all that matters is the space that it occupies.

This can be illustrated by drawing an outline. I’m using the value 10px instead of 1px for clarity:

.nav-primary li.level0 a:after {
    content: "";
    padding-right: 10px;
    margin-left: -10px;
    outline: solid red;
}
<div class=nav-primary>
  <ul>
     <li class=level0><a href=foo>bar</a>xxx
     <li><a href=foo>bar</a>xxx
  </ul>
</div>



回答2:


I ran into a similar situation which was fixed by adding display: block to the :before styles.




回答3:


To my knowledge it is possible to use CSS pseudoelements with blank content. The attribute content needs to be specified but can be left blank (as you did in your example code).

I would think that your issue could be related to the display mode - pseudoelements are inline by default. If I understand well what you're trying to achieve, I would go this way:

  • Set display mode to inline-block.
  • Specify concrete dimensions of your offset alignment (width, height).

See JSFiddle.



来源:https://stackoverflow.com/questions/26778351/using-the-after-css-pseudo-element-without-inserting-content

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