300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > html如何用百分比绝对定位 CSS相对定位和绝对定位使用百分比的计算逻辑

html如何用百分比绝对定位 CSS相对定位和绝对定位使用百分比的计算逻辑

时间:2023-01-01 03:41:46

相关推荐

html如何用百分比绝对定位 CSS相对定位和绝对定位使用百分比的计算逻辑

需求

页面需要实现自适应布局,因此使用百分比计算

测试

页面主要使用相对定位和绝对定位,主要从这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。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。