300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > CSS相对定位 绝对定位【HTML】

CSS相对定位 绝对定位【HTML】

时间:2019-04-12 06:29:55

相关推荐

CSS相对定位 绝对定位【HTML】

web前端|html教程

CSS相对定位、绝对定位

web前端-html教程

CSS定位属性:position。

督办系统 源码,Ubuntu删除lvm分区,tomcat 体系架构图,爬虫 生产环境,php快速读取excel,杨帆seolzw

定位的基本思想:定义元素框相对于其正常位置应该出现的位置,或者相对于父元素、另一个元素或浏览器窗口本身的位置。

论坛源码.net,vscode 移动代码,本田ubuntu服务器连接不上,tomcat返回很慢,sqlite c使用教程,帝国cms 插件在哪,bs前端现在都用什么框架,爬虫如何用才合法,微信sdk php,南平seo介绍,cms网站后台模版,投票网页模板,手机详情关联模板代码lzw

position属性值:static、relative、absolute、fixed。

江湖家居免费源码,安卓ubuntu主题,宝塔能不能替代TOMCAT,爬虫学期刊,在线post测试生成php代码,seo排名思路lzw

以下所有测试在Firefox40.0下进行。

所用到基本代码:

1 2 body{ 3 margin: 30px 0 0 30px; 4 padding: 0; 5 } 6 .div1{ 7 width: 200px; 8 height: 200px; 9 padding: 50px;10 background: red;11 }12 .div2{13 width: 50px;14 height: 50px;15 background-color: blue;16 }17 .div3{18 background-color: pink;19 width: 80px;20 height: 50px;21 }22 .div4{23 background-color: gray;24 width: 80px;25 height: 50px;26 }27

1 2

div2

div1

3

div3

4

div4

5

普通定位:static,默认情况。不设置position属性时,会按照正常的文档流进行排列。

固定定位:fixed,绝对定位的第二种情况(见下文)。

相对定位:relative,元素框偏移某个距离(相对于它原来的位置),它原本的位置空间仍然保留。

1 .div3{2background-color: pink;3width: 80px;4height: 50px;5position: relative;6left: 300px;7 }

DIV3向左偏移了300px,原来的位置还在(DIV4并没有贴上去)。

在元素有父元素的情况下,也是一样的。

1 .div2{2width: 50px;3height: 50px;4background-color: blue;5position: relative;6left: 250px;7 }

绝对定位:元素框在正常文档流中所占据空间关闭,并相对于其包含框定位。包含框可能是文档中的另一个元素框或者是窗口本身。元素定位后生成一个块级框,而不论原来它在正常流中生成何种类型的框。

分两中情况:

父元素/祖先元素定位方式为relative或absolute,则相对于此父元素/祖先元素定位,定位起点为父元素/祖先元素的左上角。请注意:如果父元素/祖先元素设置了padding,则从内边距左上角开始定位。 父元素/祖先元素都没有相对或绝对定位,则相对于浏览器窗口定位(相对于窗口的左上角,不考虑body的内外边距)。

第一种情况:

.div1{ position: relative; width: 200px; height: 200px; padding: 50px; background: red;}.div2{ position: absolute; left: 300px; top: 0; width: 50px; height: 50px; background-color: blue;}

从上图明显看到,DIV2向左偏移300px,是从内边距左上角开始的,而不是DIV2原始的位置(如果padding为0,则是从原始的位置)。

设置DIV1的外边距为30px,DIV2偏移left、top都为0。

1 .div1{ 2position: relative; 3margin: 30px; 4width: 200px; 5height: 200px; 6padding: 50px; 7background: red; 8 } 9 .div2{10position: absolute;11left: 0;12top: 0;13width: 50px;14height: 50px;15background-color: blue;16 }

可见,在父元素框有外边距的情况下,偏移也是从内边距开始的。

第二种情况:

body内边距增加30px,DIV2向右偏移360px。

body{ margin: 30px 0 0 30px; padding: 30px;}.div1{ width: 200px; height: 200px; padding: 50px; background: red;}.div2{ position: absolute; left: 360px; top: 60px; width: 50px; height: 50px; background-color: blue;}

左边body空白处有外边距、内边距各30px,DIV2偏移30px+30px+300px=360px,刚好与DIV1对齐。证明偏移是从窗口的左上角,而不用管内外边距!

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