css absolute定位问题

我有一个div要绝对定位在左上方,请问下面两种写法区别在哪里?

div{
    position: absolute;
    left:0;
    top:0;
}


div{
    position: absolute;
    left:0;
    top:0;
    right:0;
    bottom:0;
}
阅读 2.5k
4 个回答

第一种写法只是定位。
第二种写法会撑满距离自己最近的有定位属性的父级节点。

mozilla的文档这样写

When both top and bottom are specified, as long as height is
unspecified, auto, or 100%, both top and bottom distances will be
respected. Otherwise, if height is constrained in any way, the top
property takes precedence and the bottom property is ignored.

也就是,你的后一种写法可能导致div的大小拉大为全屏,如果div大小已经被限制住,right和bottom会被忽略。

第一种只是元素的定位; 第二种写法既有元素定位也设置了元素的大小,将元素撑开到设置了定位为非static父节点的大小

如果非全屏用第一种,全屏用第二种

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题