Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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.

like image 592
cassln Avatar asked May 19 '16 08:05

cassln


People also ask

Is absolute position relative to parent?

Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.

Can position fixed be relative to parent?

fixed : the element is removed from the flow of the document like absolutely positioned elements. In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.

How do you use position relative and absolute position?

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.


1 Answers

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>
like image 129
Paulie_D Avatar answered Oct 06 '22 08:10

Paulie_D