伪元素的CSS影响父元素
我设置了一个 测试用例,其中显示 CSS 伪元素 (::after)鼠标悬停在给定(父)元素上时。到目前为止,一切工作正常,但伪元素的负上边距影响父元素而不是生成的元素。 (虽然负左边距按预期工作。)
任何人都可以解释这种行为和/或知道解决方法吗?
I've set up a test case, where a CSS pseudo-element (::after) is displayed on mouse-hover on the given (parent-) element. Everything works fine so far, but the negative top-margin for the pseudo-element affects the parent instead of the generated element. (While the negative left-margin works as expected.)
Can anyone explain this behavior and/or know a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先要注意的是,当您使用
::after
时,DOM 如下所示:因此,其行为方式完全相同*:(使用 Chrome 或 Firefox)< /em>
http://jsfiddle.net/MLThM/7/
并删除了一些无关的属性:
http://jsfiddle.net/MLThM/8/
父元素移动的原因是折叠边距。
“修复”该问题的一种方法是将
overflow:hidden
添加到.land
:http://jsfiddle.net/MLThM/9/
并且修复应用于您的原始演示:< br>
http://jsfiddle.net/MLThM/10/
* = 让我们忘记可能的错误目前,在
::after
和::before
中,它们与当前问题无关。The first thing to be aware of is that when you use
::after
, the DOM looks like this:So, this behaves in exactly* the same way: (use Chrome or Firefox)
http://jsfiddle.net/MLThM/7/
And with some extraneous properties removed:
http://jsfiddle.net/MLThM/8/
The reason that the parent element moves is collapsing margins.
One way to "fix" that is to add
overflow: hidden
to.land
:http://jsfiddle.net/MLThM/9/
And the fix applied to your original demo:
http://jsfiddle.net/MLThM/10/
* = let's forget about possible bugs in
::after
and::before
for the moment, they aren't relevant to the current question.您始终可以将容器 div 设置为
position:relative
,然后将新内容设置为absolute
。这样您就不会影响包含 div 上的任何边距。示例: http://jsfiddle.net/MLThM/6/
You could always set your container div to
position:relative
and then the new content toabsolute
. This way you won't affect any of the margins on the containing div.Example : http://jsfiddle.net/MLThM/6/