批改状态:合格
老师批语:其实定位的出现是早于浮动的
1. 实例演示如何消除子元素浮动造成父元素高度折叠的影响
<style>
.box1 {
width: 200px;
border: 5px dashed red;
overflow: hidden;
}
.box2 {
width: inherit; /* 200px */
height: 200px;
background-color: lightblue;
}
</style>
<div>
<!-- 嵌套 : 清除浮动的影响-->
<div class="box1">
<div class="box2">
子元素区块
</div>
</div>
</div>点击 "运行实例" 按钮查看在线实例
2. 实例演示三列布局的实现原理( 绝对定位实现, 浮动定位实现)
<style>
/*页面容器*/
.container {
width: 1000px;
margin: 0 auto;
}
/*头部与底部共用样式*/
.header, .footer {
height: 60px;
background-color: lightgrey;
}
/*主体*/
.main {
/*min-height: 800px;*/
margin: 5px auto;
background-color: lightblue;
position: relative;
}
/*主体三部分的基本样式*/
.left {
width: 200px;
/*设置最小高度,可以确保在没有内容的情况下,仍能显示出高度来*/
min-height: 800px;
background-color: lightgreen;
position: absolute;
left: 0;
top: 0;
}
.content {
/*内容区宽度自适应*/
min-height: 800px;
background-color: lightseagreen;
margin-left: 210px;
margin-right: 210px;
}
.right {
width: 200px;
min-height: 800px;
background-color: lightpink;
position: absolute;
right: 0;
top: 0;
}
</style>
<div>
<div class="container">
<div class="header">头部</div>
<!-- 三列布局: 绝对定位 -->
<div class="main">
<div class="left">左侧</div>
<div class="content">内容区</div>
<div class="right">右侧</div>
</div>
<div class="footer">底部</div>
</div>
</div>点击 "运行实例" 按钮查看在线实例
<style>
/*页面容器*/
.container {
width: 1000px;
margin: 0 auto;
}
/*头部与底部共用样式*/
.header, .footer {
height: 60px;
background-color: lightgrey;
}
/*主体*/
.main {
/*min-height: 800px;*/
margin: 5px auto;
background-color: lightblue;
overflow: hidden;
}
/*主体三部分的基本样式*/
.left {
width: 200px;
min-height: 800px;
background-color: lightgreen;
float: left;
}
.content {
/*内容区宽度自适应*/
min-height: 800px;
background-color: lightseagreen;
float: left;
width: 580px;
margin-left: 10px;
}
.right {
width: 200px;
min-height: 800px;
background-color: lightpink;
float: right;
}
</style>
<div>
<!-- 浮动定位 -->
<div class="container">
<div class="header">头部</div>
<div class="main">
<div class="left">左侧</div>
<div class="content">内容区</div>
<div class="right">右侧</div>
</div>
<div class="footer">底部</div>
</div>
</div>点击 "运行实例" 按钮查看在线实例
3.总结
1)对父元素使用overflow: hidden;可以清除子元素浮动对父元素的影响
2)三列布局,一般指两端固定宽度,中间宽度自适应的布局方式,这种布局应用十分广泛。
实现方式大方向来看有差不多四种:1、绝对定位;2、两侧浮动+中间自动撑开;3、圣杯布局和双飞翼布局;4、通过特定布局实现,比如flex/grid/table布局;
其中绝对定位可以算是最简单的一种了,关键点在于中间版块不给宽度,通过左右绝对定位left和right实现自适应;
两侧浮动很简单,只需要用到float即可,中间自适应的方式有很多,可以通过display:block实现,也可以通过calc()计算出宽度,或者给左右固定margin等方式实现。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号