需求
页面需要实现自适应布局,因此使用百分比计算
测试
页面主要使用相对定位和绝对定位,主要从这2方面进行比对测试
相对定位
html, body {
margin: 0;
padding: 0;
}
#wrapper{
width: 1000px;
height: 1000px;
border: 1px solid green;
position: relative;
}
#middle{
width: 600px;
height: 600px;
border: 1px solid blue;
}
#inner{
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
top: 10%;
}
此时top换算成像素为60px,即相对定位使用百分比的时候,参照的是最近一层父元素的高度
绝对定位
html, body {
margin: 0;
padding: 0;
}
#wrapper{
width: 1000px;
height: 1000px;
border: 1px solid green;
position: relative;
}
#middle{
width: 600px;
height: 600px;
border: 1px solid blue;
}
#inner{
width: 300px;
height: 300px;
border: 1px solid red;
position: absolute;
top: 10%;
}
此时top换算成像素为100px,即绝对定位使用百分比的时候,参照的是最近一层父元素的高度,但父元素不能是static定位;若父元素是static定位,则会一直往上一级查找,直至查询到整个网页的根元素html
总结
top(bottom) left(right)在相对定位中使用百分比时,参照的是最近一层父元素的高度与宽度;
top(bottom) left(right)在绝对定位中使用百分比时,参照的是最近一层父元素的高度与宽度,但父元素不能是static定位;若父元素是static定位,则会一直往上一级查找,直至查询到整个网页的根元素html。