Reputation: 785
Now I am absolutely confused. I have created a little arrow (with css) nested inside a parent div that has overflow hidden with the idea in mind to move the arrow a little out at mouseover on its parent. The parent element is horizontally centered and for (some other) good reasons it has absolute positioning.
html:
<div id ="arrowContainer">
<div id="arrow" class="arrow_left"></div>
</div>
CSS:
#arrowContainer {
position: absolute;
height: 54px;
width: 13px;
bottom: 4.2%;
left: 50%;
margin-left: -9px;
overflow: hidden;
cursor: pointer;
}
.arrow_left {
position: absolute;
width: 0;
height: 0;
padding: 0;
top: 10px;
right: -4px;
border-top: 13px solid transparent;
border-bottom: 13px solid transparent;
border-right: 13px solid #fff;
opacity: 0.72;
}
result:
Ok. Now I wanted that the mouseover area of the parent extends a little more to the sides. And I thought, well, use some padding. So I changed the parents CSS:
#arrowContainer {
position: absolute;
height: 54px;
width: 13px;
bottom: 4.2%;
left: 50%;
margin-left: -32px;
padding: 0 24px;
overflow: hidden;
cursor: pointer;
}
which leads to the more me unexpected result:
1) Not only that I had to encounter the padding in a new margin-left value, but ok, not so hard to do.
2) But why the hell my child with right: -4px value is positioned relative to the right of the padding and not the visible area (blue) of its parent any longer???
Ok. I know that I could use another container for both to fix this. But this I do not want! There must be a regular way to solve this with 2 divs only. What is my mistake here? Thanks so much!
Upvotes: 0
Views: 4019
Reputation: 444
But why the hell my child with right: -4px value is positioned relative to the right of the padding and not the visible area (blue) of its parent any longer???
That's unfortunately how padding works. Padding adds space inside your element which moves the outer edges of your relative positioned element.
But there's is a solution. Instead of using top, bottom, left, right use margin to position your element.
When you add a element with the position:absolute;
without setting any top, left, right or bottom position the element will be taken out of the normal flow. If you then position it by modifying its margins it will not get affected by the padding.
JSBin: http://jsbin.com/bowofejuzu/1/edit?html,css,output
HTML:
<div class ="container">
<div class="element"></div>
</div>
CSS:
.container {
position:relative;
width:20px;
height:100px;
background-color:#CCC;
padding:0 40px;
}
.element {
position: absolute;
width: 15px;
height: 15px;
background-color:red;
margin: 40px 0 0 5px;
}
Upvotes: 2