cassln cassln - 6 months ago 13
HTML Question

How to absolute position :before pseudo element of child relative to parent?

Here is the fiddle.

I have two div elements.


<div class="parent">
<div class="child">
</div>
</div>


And CSS code for that.

.parent {
height: 20px;
width: 100px;
background-color: #080;
position: relative;
}

.child {
position: absolute;
width: 80px;
height: 200px;
background-color: #008;
right: -10px;
top: 30px;
}

.child:before {
border-right: 10px solid transparent;
border-bottom: 10px solid #008;
border-left: 10px solid transparent;
top: -10px;
width: 0;
height: 0;
content: "";
position: absolute;
left: 50%;
}


How to position
.child:before
related to
.parent
without JS. I know solution with
.parent:before
, but it is not good for me.

Answer

I think this is what you are trying to do.

I think you will find this more robust and scalable.

.parent {
  height: 20px;
  width: 100px;
  background-color: #080;
  position: relative;
}
.child {
  position: absolute;
  width: 80px;
  height: 200px;
  background-color: #008;
  left: 50%;
  /* note 50% */
  top: 30px;
  margin-left: -20px;
  /* 2x your arrow size */
}
.child:before {
  position: absolute;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #008;
  border-left: 10px solid transparent;
  top: -10px;
  /* your border size */
  margin-left: 10px;
  /* your border-size */
  width: 0;
  height: 0;
  content: "";
  left: 0;
}
<div class="parent">
  <div class="child">
  </div>
</div>