在写css的时候,遇到需要使用绝对定定位时,我惯常的思维是直接先top/bottom和left/right先设置为0,再调整具体的位置。这样做可以根据设计稿的尺寸,一步步定位到目标位置。
当然也正是这种不需要关心定位值是关于具体什么位置定位的思路,导致我时常需要看实际效果才能解决问题,所以对于此还是不清楚:若包含块具有padding时,设top和left为0后,元素是定位在内容区域的左上角还是包括padding区域的左上角?甚至是border或margin的左上角?
我尝试了做了一个小demo
得到的结果:基于包含块的padding进行的定位。为此,我也查阅了mdn,参考里面对于top的解释:
top:
When
positionis set toabsoluteorfixed, thetopproperty specifies the distance between the element's outer margin of top edge and the inner border of the top edge of its containing block.(定位设置为absolute或fixed后,top属性所确定的距离是元素顶部边缘的外部margin到其包含块的上边缘的内border)
所以说,元素绝对定位后,top等属性是根据border的内边缘(同样也是padding的外边缘)进行的距离定位,问题解决~