网页布局的核心就是利用css摆放盒子的位置
css定位机制有3种分为了 普通流 浮动 定位
普通流:网页元素按照标签从上往下从左到右进行排序
浮动:让元素脱离文档流不占位置会影响标准流
代码实例
<style>
div:first-child{
width: 100px;
height: 100px;
border: 1px solid #FF8500;
float: left; /*将第一个div进行左浮动*/
} div:last-child{
width: 100px;
height: 100px;
border: 1px solid red;
background-color: #FF8500;
}
</style>
</head>
<body>
<div></div>
<div></div>
</body>
效果
当第一个div浮动后,div脱离了文档流,不占位置,那么此时第二个div就占据了第一个div的位置,这就是浮动,脱离文档流你就想像成现在网页html种不存在这个元素
定位:定位模式分为静态定位,绝对定位,相对定位,固定定位,定位还分为边偏移,边偏移和定位模式一起组成了定位
静态定位:元素默认采用静态定位,就是从上往下,从左到右排列
相对定位相对定位以元素本身左上角 (0,0)为参照点,相对定位 relative,占据位置,元素移动后,原来的位置依然保留
代码实例
/*普通的*/
<style>
div{
width: 200px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div></div>
</body>
元素默认出现在了浏览器左上角
此时我们添加相对定位
代码实例
<style>
div{
width: 200px;
height: 100px;
background-color: red;
position: relative; /*相对定位 relative 默认是 静态定位 static*/
top: 100px; /边偏移:向下移动100px 向左移动200px/
left: 200px;
}
</style>
</head>
<body>
<div></div>
</body>
此时元素移动到了这位置坐标为(200,100),这就是相对定位,以自己左上角为基点
绝对定位
绝对定位顾名思义想出现哪里就出现在哪里,绝对定位和浮动一样脱离文档流不占位置,因此布局中经常使用
代码实例
<style>
div{
width: 200px;
height: 100px;
background-color: red;
position: absolute; /*absolute代表绝对定位*/
right: 0; /*靠右边*/
bottom: 0; /*靠下边*/
}
</style>
</head>
<body>
<div></div>
</body>
效果
可以看到默认出现在左上角的图片被我们通过定位移动到了右下角
绝对定位的特性:绝对定位会找拥有定位的父元素,以父元素为参照点,如果父元素都没有定位的话那么以浏览器为准,上述代码中,绝对定位的基点是浏览器 body (0,0)点因为他的父亲没有添加定位
子绝父相模式:意思是子元素用相对定位,父元素用绝对定位,这个模式是最常用的
代码实例
.father{
width: 400px;
height: 400px;
background-color: #4182FA;
margin: 200px auto;
}
.son{
width: 100px;
height: 100px;
background-color: #FF8500;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
这段代码中父元素里面包裹了一个子元素
此时我们想使用绝对定位将里面的子元素移动到右下角
.father{
width: 400px;
height: 400px;
background-color: #4182FA;
/*position: relative; !*给父元素添加了相对定位*!*/
margin: 200px auto;
}
.son{
width: 100px;
height: 100px;
background-color: #FF8500;
position: absolute; /*添加了绝对定位*/
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
实例
此时奇怪的事情发生了我们是想将子盒子移动到父盒子的下方,为什么子盒子跑到了浏览器的下方了这就是我们说的绝对定位的特性
绝对定位的特性**:绝对定位会找拥有定位的父元素,以父元素为参照点,如果父元素都没有定位的话那么以浏览器为准,上述代码中,绝对定位的基点是浏览器 body (0,0)点因为他的父亲没有添加定位
解决方法:给父亲添加定位,一般我们都给父亲添加相对定位,因为相对定位不脱离文档流,占位置,我们可以想一下,如果给父亲添加绝对定位,那么父亲也会出现这个问题。‘
代码实例
.father{
width: 400px;
height: 400px;
background-color: #4182FA;
position: relative; /*给父元素添加了相对定位*/
margin: 200px auto;
}
.son{
width: 100px;
height: 100px;
background-color: #FF8500;
position: absolute;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
效果
这就是常用的子绝父相
总结:网页布局的核心就是利用css摆放盒子的位置,摆放盒子常用的就是定位,和浮动,利用这两大特性可以轻松构建布局