CSS相对定位、绝对定位
2024-08-26 03:27:40
CSS定位属性:position。
定位的基本思想:定义元素框相对于其正常位置应该出现的位置,或者相对于父元素、另一个元素或浏览器窗口本身的位置。
position属性值:static、relative、absolute、fixed。
以下所有测试在Firefox40.0下进行。
所用到基本代码:
<style>
body{
margin: 30px 0 0 30px;
padding:;
}
.div1{
width: 200px;
height: 200px;
padding: 50px;
background: red;
}
.div2{
width: 50px;
height: 50px;
background-color: blue;
}
.div3{
background-color: pink;
width: 80px;
height: 50px;
}
.div4{
background-color: gray;
width: 80px;
height: 50px;
}
</style>
<body>
<div class="div1"><div class="div2">div2</div>div1</div>
<div class="div3">div3</div>
<div class="div4">div4</div>
</body>
普通定位:static,默认情况。不设置position属性时,会按照正常的文档流进行排列。
固定定位:fixed,绝对定位的第二种情况(见下文)。
相对定位:relative,元素框偏移某个距离(相对于它原来的位置),它原本的位置空间仍然保留。
.div3{
background-color: pink;
width: 80px;
height: 50px;
position: relative;
left: 300px;
}
DIV3向左偏移了300px,原来的位置还在(DIV4并没有贴上去)。
在元素有父元素的情况下,也是一样的。
.div2{
width: 50px;
height: 50px;
background-color: blue;
position: relative;
left: 250px;
}
绝对定位:元素框在正常文档流中所占据空间关闭,并相对于其包含框定位。包含框可能是文档中的另一个元素框或者是窗口本身。元素定位后生成一个块级框,而不论原来它在正常流中生成何种类型的框。
分两中情况:
- 父元素/祖先元素定位方式为relative或absolute,则相对于此父元素/祖先元素定位,定位起点为父元素/祖先元素的左上角。请注意:如果父元素/祖先元素设置了padding,则从内边距左上角开始定位。
- 父元素/祖先元素都没有相对或绝对定位,则相对于浏览器窗口定位(相对于窗口的左上角,不考虑body的内外边距)。
第一种情况:
.div1{
position: relative;
width: 200px;
height: 200px;
padding: 50px;
background: red;
}
.div2{
position: absolute;
left: 300px;
top:;
width: 50px;
height: 50px;
background-color: blue;
}
从上图明显看到,DIV2向左偏移300px,是从内边距左上角开始的,而不是DIV2原始的位置(如果padding为0,则是从原始的位置)。
设置DIV1的外边距为30px,DIV2偏移left、top都为0。
.div1{
position: relative;
margin: 30px;
width: 200px;
height: 200px;
padding: 50px;
background: red;
}
.div2{
position: absolute;
left:;
top:;
width: 50px;
height: 50px;
background-color: blue;
}
可见,在父元素框有外边距的情况下,偏移也是从内边距开始的。
第二种情况:
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对齐。证明偏移是从窗口的左上角,而不用管内外边距!
最新文章
- CSS3 @font-face的使用
- 剪短的python数据结构和算法的书《Data Structures and Algorithms Using Python》
- ResultSet相关ResultSetMetaData详细
- vs c# int &; int32
- C#基础——谈谈.NET异步编程的演变史
- 6、四大组件之二-Service初步
- mongoDB单元测试
- Windows、Linux -- 远程登录、文件传输、文件共享
- shell 之解释器、变量、字符串、数组
- 增强for
- ES6箭头函数Arrow Function
- 让div固定在顶部不随滚动条滚动【转】
- docker 安装redis
- P4173 残缺的字符串 fft
- 将url的参数解析为Json数据
- python开发_glob
- 32位 64位 获得进程peb的方法
- Oracle physical dataguard with broker部署
- javascript 实现购物车页面
- Unity Json解析IPA
热门文章
- IronPython 源码剖析系列(2):IronPython 引擎的运作流程
- android:layout_weight详解
- Learning WCF 书中的代码示例下载地址
- hadoop2.2编程:序列化
- 【转】JAVA字符串格式化-String.format()的使用--不错
- ActionBar 中setDisplayHomeAsUpEnabled和setHomeButtonEnabled和setDisplayShowHomeEnabled方法的理解
- 杨佩昌:中国官员去德国考察看什么两眼发光 z
- HDU-2523 SORT AGAIN
- selenium webdriver(6)---cookie相关操作
- JavaScript---网络编程(12)--DHTML技术演示(5)-form表单验证技术(正则)