使用:after CSS伪元素,不插入内容 [英] Using the :after CSS pseudo-element without inserting content
问题描述
可以使用:after
CSS伪元素来偏移对齐,而不会在 content:
。除非指定内容,否则它似乎不会渲染,所以只是想知道这是否可能或是否有任何已知的解决方法。
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.
例如: -
.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.
推荐答案
可以使用:
伪元素后面加上 content
属性设置为空字符串,但不设置为全部(因此它的初始值
none
,这意味着伪元素根本不会生成)。
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.
这可以通过绘制一个大纲来说明。为了清晰起见,我使用的值为10px,而不是1px:
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>
这篇关于使用:after CSS伪元素,不插入内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!