批改状态:合格
老师批语:关于绝对定位, 总结的很到位
子元素的浮动和清除浮动
父元素没有设置高度,会被子元素撑起,当子元素有浮动的时候,父元素的高度会被折叠。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box1 {
width: 300px;
border: 1px solid red;
}
.box2,
.box3 {
width: 200px;
height: 200px;
background: lightseagreen;
}
.box3 {
float: left;
}
.box4 {
overflow: hidden;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">box2没有浮动,box1被子元素box2撑起</div>
</div>
<hr>
<div class="box1">
<div class="box3">box3浮动,box1元素高度折叠</div>
</div>
<div style="clear: both;"></div>
<hr>
<div class="box1 box4">
<div class="box3">box4加上overflow: hidden; box1清除浮动再次有了高度</div>
</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例

绝对定位布局
中间块main给一个固定高度,并且做相对定位,内部区域左右块做左右浮动,两边浮动块宽度相同,中间块左右居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.header,
.footer {
height: 80px;
background: lightslategray;
}
.main {
height: 500px;
position: relative;
}
.left {
height: inherit;
background: lightgreen;
width: 20%;
position: absolute;
left: 0;
top: 0;
}
.content {
height: inherit;
background: lightpink;
width: 60%;
/* margin: 0 20%; */
margin: 0 auto;
}
.right {
height: inherit;
background: lightskyblue;
width: 20%;
position: absolute;
right: 0;
top: 0;
}
</style>
</head>
<body>
<div class="header">header</div>
<div class="main">
<div class="left">left</div>
<div class="content">content</div>
<div class="right">right</div>
</div>
<div class="footer">footer</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例

浮动定位布局
中间块main没有给高度,内部三个块有高度,并且有左浮动,给main一个overflow:hidden;清除对底部footer的影响。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.header,
.footer {
height: 80px;
background: lightslategray;
}
.main {
overflow: hidden;
}
.left {
height: 500px;
background: lightgreen;
width: 20%;
float: left;
}
.content {
height: 500px;
background: lightpink;
width: 60%;
float: left;
}
.right {
height: 500px;
background: lightskyblue;
width: 20%;
float: left;
}
</style>
</head>
<body>
<div class="header">header</div>
<div class="main">
<div class="left">left 左浮动 高500px</div>
<div class="content">content 左浮动 高500px</div>
<div class="right">right 左浮动 高500px</div>
</div>
<div class="footer">footer</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例

小结:浮动的元素对后面非浮动的元素有影响,会当它不存在,发生重叠现象;清除浮动的方法有在后面的块元素添加clear:both,在浮动元素父级添加overflow:hidden;相对定位relative,是相对于自身位置进行定位,定位后仍然占据原来的空间。绝对定位position,是距离第一个具有定位属性的父元素来定位,在没有父元素设置定位的话,默认就是以body来定位的。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号