1

See my codepen: http://codepen.io/Chiz/pen/NAmdvr

In the :before pseudo element, I set a top and left margin of 20px each.

However, the top 20px margin seems to be applied to the main element itself (the div), while the left 20px margin seems to be applied to the :before element itself.

Why is this?

.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>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Illo Yonex Illo
  • 247
  • 2
  • 6

2 Answers2

2

The top margins of both the element and the :before pseudo-element are 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.

Margin collapsing behavior is the same whether the boxes belong to elements or pseudo-elements. In other words, as far as CSS is concerned, the two boxes are in-flow block boxes with adjoining top margins — whether these boxes were generated by elements or pseudo-elements is irrelevant, since your :before pseudo-element has a display: block declaration (this would matter if it didn't, since the default display of :before pseudo-elements is inline).

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

change the display:block to 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>
Shahil M
  • 3,836
  • 4
  • 25
  • 44