I am trying to align two boxes with same dimensions. The first is a div and second is the :before
pseudo-element of the div, but for some reason the pseudo-element is positioned with -1px at the bottom and the boxes are not aligned. I can't understand why that is. It seems the browser add a positioning distance for no reason and when border is removed it all works. Is this a browser bug or I am doing something wrong.
div {
position: relative;
width: 50px;
height: 50px;
border: 1px solid;
}
div::before {
position:absolute;
content: '';
left: 50px;
width: 50px;
height: 50px;
border: 1px solid;
}
<div></div>
The <div>
's content is only whats inside of the border. The border itself is not part of the <div>
's content which the ::before
is relatively positioned to. The ::before
behaves as expected because its top
position is relative to the <div>
's content-area, not the <div>
including its border. If you change the border to 2px you will notice the difference will be 2px then. A top
of -1px would indeed fix this issue, but not in a generic way.
The best way to fix this issue is by using a container <div>
serving as the relative block instead of the owning <div>
of the ::before
:
.container {
position: relative;
}
.inner {
width: 50px;
height: 50px;
border: 1px solid;
}
.inner::before {
position:absolute;
top: 0;
content: '';
left: 50px;
width: 50px;
height: 50px;
border: 1px solid;
}
<div class="container">
<div class="inner"></div>
<div>
Another way would be to use an outline
value or a box-shadow: box-shadow: 0 0 0 1px black;
. These don't affect the size of the <div>
using it.