4

Can anyone point me to specs and clarify this for me? If I don't set left to 0, it won't align. Why doesn't it just align at the default auto value?

http://codepen.io/geoyws/pen/EKqWjQ

geoyws
  • 3,326
  • 3
  • 35
  • 47

3 Answers3

1

The CSS spec says, for the width of absolutely positioned, non-replaced elements:

The static position for 'left' is the distance from the left edge of the containing block to the left margin edge of a hypothetical box that would have been the first box of the element if its 'position' property had been 'static' and 'float' had been 'none'

...

If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0. Then, [...] set 'left' to the static position

The static position will be after the left padding of the .button div.

Alohci
  • 78,296
  • 16
  • 112
  • 156
  • It makes sense: the hypothetical box would be affected by the padding of the containing element. Thanks very much! – geoyws May 23 '16 at 07:54
  • hi @Alohci, you may probably find few minutes to check this one : https://stackoverflow.com/questions/52677653/fixed-html-elements-are-not-always-positioned-with-respect-to-viewport-so-w?noredirect=1#comment92285679_52677653 ... I closed as duplicate and trying to explain but with no avail. I think you will probably have better words to expain to him (or maybe am completely wrong ..) – Temani Afif Oct 06 '18 at 12:38
0

It happens because by default most of the html elements has specific margin or padding properties. Here in this case When you set its left property to '0', there it resets itself and removes all the pre-define property values.

Thats the reason it aligns perfectly to '0' and not to 'auto'.

0

Because of if you didn't specify the position property of an absolute element it will respect the padding of his parent element such in your case. but if you specified it such giving left:0 then it will start form the left border of his parent and ignore the padding

.button {
  position: relative;
  background: green;
  padding: 10px 0;
   
  
}

.right_underneath {
  position: absolute;
  top: 100%; /* refers to parent element */
  left: auto; /* if set to 0, it aligns perfectly, but why does it not do so at `auto`? */
  padding: 10px;
  background: yellow;
}
<div class="button">
  <div class="right_underneath">
    <input type="text"/>
  </div>
</div>