请问relative设置偏移为百分比的效果
请问我为relative的元素设置了top和left百分比,
left起作用, top不起作用, 这是怎么回事呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <!DOCTYPE html> <html> <head> <meta charset= "UTF-8" > <title>Document</title> </head> <style type= "text/css" > .parent{ width: 300px; height: 300px; border: 1px solid red; background: gray; position: relative; top:50%; left:50%; } .block{ height: 100px; width: 100px; border: 1px solid red; background: blue; position: absolute; top:50%; left:50%; margin-left: -50px; margin-top: -50px; } </style> <body> <div class= "parent" > <div class= "block" ></div> </div> </body> </html> |
17
收起
正在回答
4回答
你好,百分比这个值是以父级为参考的,就是说,是父级的百分之多少,但是这里parent的父级是body,而浏览器中,body是默认高度,并不是浏览器的可视区域高度。但是body的默认宽度是浏览器的可视区域宽度。所以,body的高度是0px,但是宽度是浏览器的宽度。
所以这里top设置百分比没有生效,但是left有效,建议:可给body设置下高度。例:可参考如下,设置百分比,也可以设置具体的高度。
1 2 3 | html,body{ height : 100% ; } |
祝学习愉快~
前端小白入门系列课程
- 参与学习 人
- 提交作业 11218 份
- 解答问题 36712 个
从一个不会编程的小白到一个老司机是需要过程的,首先得入门,学习基础知识,然后才能进阶,最后再到精通,本专题是你走进前端世界的不二选择!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧