批改状态:合格
老师批语:其实定位的作用, 比浮动大, 要重点掌握
本节课学习了CSS浮动和定位得用法,知识点较多。
1、消除子元素浮动造成父元素高度折叠的影响

消除父元素高度折叠方法一:父元素增加overflow: hidden属性
<style>
.box1 {
width: 500px;
border: 5px dashed red;
overflow: hidden;
}
.box2 {
width: inherit;
height: 500px;
background-color: lightpink;
float: left;
}
</style>
<div class="box1">
<div class="box2"></div>
</div>点击 "运行实例" 按钮查看在线实例
消除父元素高度折叠方法二:clear:both清除浮动
<style>
.box1 {
width: 500px;
border: 5px dashed red;
}
.box2 {
width: inherit;
height: 500px;
background-color: lightpink;
float: left;
}
</style>
<div class="box1">
<div class="box2"></div>
<div style="clear:both"></div>
</div>点击 "运行实例" 按钮查看在线实例
2、 用绝对定位、浮动分别实现三列布局
CSS浮动实现三列布局

<style>
.box {
width: 1200px;
overflow: hidden;
}
.box1 {
width: 200px;
background-color: lightcoral;
min-height: 800px;
float: left;
}
.box2 {
width: 800px;
min-height: 800px;
background-color: lightblue;
float: left;
}
.box3 {
width: 200px;
background-color: lightgreen;
min-height: 800px;
float: left;
}
</style>
<div class="box">
<div class="box1">左侧</div>
<div class="box2">中间</div>
<div class="box3">右侧</div>
</div>点击 "运行实例" 按钮查看在线实例
绝对定位实现三列布局

<style>
body {
margin: 0;
}
.main {
width: 600px;
position: absolute;
}
.left,
.content,
.right {
width: 200px;
}
.left {
min-height: 800px;
background-color: lightgreen;
position: absolute;
left: 0;
top: 0;
}
.content {
min-height: 800px;
background-color: lightcoral;
margin: 0 200px;
}
.right {
min-height: 800px;
background-color: lightseagreen;
position: absolute;
right: 0;
top: 0;
}
</style>
<div class="main">
<div class="left">左侧</div>
<div class="content">中间</div>
<div class="right">右侧</div>
</div>点击 "运行实例" 按钮查看在线实例
总结
绝对定位:绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于最初的包含块。
相对定位:根据元素原来占据的空间进行定位。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号