请问relative设置偏移为百分比的效果

来源:2-5 position-relative

NeilSK

2018-01-17 15:13:30

请问我为relative的元素设置了top和left百分比,

left起作用, top不起作用, 这是怎么回事呢?

<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>


写回答

1回答

好帮手慕糖

2018-01-17

你好,该问题,在你的另一个问答 http://class.imooc.com/course/qadetail/36411 中已经解释了哦,

1、百分比这个值是以父级为参考的,就是说,是父级的百分之多少。

2、这里parent的父级是body,而浏览器中,body是默认高度,并不是浏览器的可视区域高度。但是body的默认宽度是浏览器的可视区域宽度。所以,body的高度是0px,但是宽度是浏览器的宽度。

3、所以这里top设置百分比没有生效,但是left的有效。

祝学习愉快~

0
heilSK
h 非常感谢!
h018-01-17
共1条回复

0 学习 · 36712 问题

查看课程