:before 元素的边距表现不一致
Margins behaving inconsistently for :before elements
查看我的代码笔:http://codepen.io/Chiz/pen/NAmdvr
在 :before 伪元素中,我分别设置了 20px 的上边距和左边距。
但是,顶部 20 像素的边距似乎应用于主元素本身(div),而左侧 20 像素的边距似乎应用于 :before 元素本身。
这是为什么?
.b
{
width:100px;
height:100px;
background-color:gray;
}
.b:before
{
content:"a";
color:white;
display:block;
width:50%;
height:50%;
background-color:rgb(40,40,40);
margin:20px 0 0 20px;
}
<div class="b"></div>
将 display:block 更改为 display:inline-block for .b:before
.b
{
width:100px;
height:100px;
background-color:gray;
}
.b:before
{
content:"a";
color:white;
display:inline-block;
width:50%;
height:50%;
background-color:rgb(40,40,40);
margin:20px 0 0 20px;
}
<div class="b"></div>
元素和 :before
伪元素的上边距均为 collapsing. This results in the margin of the :before
pseudo-element bleeding out of the element instead. This does not happen with horizontal margins. See this answer。
无论框属于元素还是伪元素,边距折叠行为都是相同的。换句话说,就 CSS 而言,这两个框是具有相邻顶部边距的流入块框——这些框是由元素还是伪元素生成的无关紧要,因为你的 :before
伪元素有一个 display: block
声明(如果没有,这会很重要,因为 :before
伪元素的默认显示是 inline
)。
查看我的代码笔:http://codepen.io/Chiz/pen/NAmdvr
在 :before 伪元素中,我分别设置了 20px 的上边距和左边距。
但是,顶部 20 像素的边距似乎应用于主元素本身(div),而左侧 20 像素的边距似乎应用于 :before 元素本身。
这是为什么?
.b
{
width:100px;
height:100px;
background-color:gray;
}
.b:before
{
content:"a";
color:white;
display:block;
width:50%;
height:50%;
background-color:rgb(40,40,40);
margin:20px 0 0 20px;
}
<div class="b"></div>
将 display:block 更改为 display:inline-block for .b:before
.b
{
width:100px;
height:100px;
background-color:gray;
}
.b:before
{
content:"a";
color:white;
display:inline-block;
width:50%;
height:50%;
background-color:rgb(40,40,40);
margin:20px 0 0 20px;
}
<div class="b"></div>
元素和 :before
伪元素的上边距均为 collapsing. This results in the margin of the :before
pseudo-element bleeding out of the element instead. This does not happen with horizontal margins. See this answer。
无论框属于元素还是伪元素,边距折叠行为都是相同的。换句话说,就 CSS 而言,这两个框是具有相邻顶部边距的流入块框——这些框是由元素还是伪元素生成的无关紧要,因为你的 :before
伪元素有一个 display: block
声明(如果没有,这会很重要,因为 :before
伪元素的默认显示是 inline
)。