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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With