定位
CSS 定位和浮动
CSS 为定位和浮动提供了一些属性,利用这些属性,可以建立列式布局,将布局的一部分与另一部分重叠,还可以完成多年来通常需要使用多个表格才能完成的任务。
定位的基本思想很简单,它允许你定义元素框相对于其正常位置应该出现的位置,或者相对于父元素、另一个元素甚至浏览器窗口本身的位置。显然,这个功能非常强大,也很让人吃惊。要知道,用户代理对 CSS2 中定位的支持远胜于对其它方面的支持,对此不应感到奇怪。
另一方面,CSS1 中首次提出了浮动,它以 Netscape 在 Web 发展初期增加的一个功能为基础。浮动不完全是定位,不过,它当然也不是正常流布局。我们会在后面的章节中明确浮动的含义。
Demo1
* {
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 200px;
}
.box1 {
background-color: red;
}
.box2 {
background-color: yellow;
/*定位*/
/*relative 相对定位*/
position: relative;
left: 100px;
top: 100px;
}
.box3 {
background-color: pink;
position: relative;
top: 10px;
}
绝对定位
Demo2
* {
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 200px;
}
.box1 {
background-color: red;
}
.box2 {
background-color: yellow;
/*定位*/
/*absolute 绝对定位*/
/*脱离了标准文档流
不占位置了
它的位置的值是以我们浏览器窗口的左上角为 0 0基准点*/
position: absolute;
top: -100px;
left: -100px;
}
.box3 {
background-color: pink;
width: 300px;
}
固定定位
demo3
body {
height: 20000px;
}
div {
height: 50px;
width: 80px;
background-color: skyblue;
text-align: center;
line-height: 50px;
/*鼠标手势*/
/*move pointer*/
cursor: pointer;
/*圆角*/
border-radius: 10px;
position: fixed;
/*没有定位 static*/
/*position: static;*/
right: 30px;
bottom: 60px;
}
div:hover {
background-color: black;
color: #fff;
}
复杂定位
* {
margin: 0;
padding: 0;
}
#father {
width: 600px;
height: 600px;
background-color: yellow;
margin: 0 auto;
margin-top:40px ;
/*position: relative;*/
}
.son {
height: 150px;
width: 150px;
}
.son1 {
background-color: red;
float: left;
}
.son2 {
background-color: green;
float: left;
/*父盒子添加定位
* */
/*position: relative;
* 父容器中一般使用相对定位
* */
position: relative;
}
.son3 {
background-color: blue;
float: left;
}
span {
display: block;
background-color: hotpink;
height: 60px;
width: 26px;
text-align: center;
position: absolute;
/*position: relative;*/
top: -20px;
left: 100px;
}
/*
* 1.定位的元素会找离他最近的加了定位的祖先元素
2.这个祖先元素我们一把会添加相对定位relative(我们不希望他飘起来)
这个定位元素(需要操作的元素)我们一般会给它添加绝对定位absolute,(我们希望他飘起来,不占位置,方便布局)
总结一句为:子绝父相(实际开发一把这么干)*/
版心和布局
Demo4
*{
margin: 0;
padding: 0;
}
.content {
background-color: #ccc;
}
.head {
width: 800px;
height: 40px;
background-color: yellow;
margin: 0 auto;
}
.container {
height: 400px;
width: 800px;
background-color: pink;
margin: 0 auto;
}
.content1 {
width: 100%;
background-color: #999;
}