一、什么是盒子模型
盒子模型(Box Model)是CSS中用于描述元素布局的核心概念。每个HTML元素都可以看作是一个矩形的盒子,这个盒子由四个部分组成:内容(content)、内边距(padding)、边框(border)和外边距(margin)。
二、文档流
概念:HTML网页默认的元素摆放机制(类似我们的书写方式,写不下就换行)
块元素的文档流(自上而下流水线摆放)
行内元素的文档流(从左到右流水线摆放)
缺陷:元素摆放布局不灵活,出现元素间高低不平(元素底边对齐但顶边不对齐),文本空间默认折叠,元素间默认空隙过小的现象。
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文档流练习</title>
</head>
<body>
<div class="content">
<p>这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。
这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。
这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。
这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。这里是内容。</p>
</div>
<span>
<img src="./屏幕截图 2025-05-19 214701.png" alt="图片加载成功">
<img src="./屏幕截图 2025-05-19 214701.png" alt="">
</span>
</body>
</html>
效果如下:
三、盒子的定位
1、相对定位
概念:相对盒子原本位置定位;盒子本体仍处于文档流中,占据原本位置。
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>相对定位练习</title>
<style>
#div1{
background-color: aqua;
position: absolute;
left: 50px;
top: 20px;
}
#div2{
background-color: brown;
position: absolute;
left: 100px;
top: 40px;
}
#div3{
background-color: gold;
position: absolute;
left: 150px;
top: 80px;
}
article{
background-color: darkgray;
position: absolute;
left: 500px;
top: 80px;
}
</style>
</head>
<body>
<article>
<div id="div1">《将进酒》</div>
<div id="div2">《赠汪伦》</div>
<div id="div3">《蜀道难》</div>
</article>
</body>
</html>
效果如下:
2、绝对定位
概念:相对于已经定位的上层元素(即设置了position属性的上层元素)进行定位;若上层元素未定位,则向更上层寻找已定位元素,直至根元素。(盒子本体会脱离文档流)
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>绝对定位练习</title>
<style>
#face{
width: 500px;
height: 500px;
background-color: bisque;
position: absolute;
left: 600px;
top: 100px;
}
#left{
width: 50px;
height: 50px;
background-color: black;
position: absolute;
left: 100px;
top: 100px;
}
#right{
width: 50px;
height: 50px;
background-color: black;
position: absolute;
right: 100px;
top: 100px;
}
#mouse{
width: 300px;
height: 60px;
background-color: deeppink;
position: absolute;
left: 100px;
top: 300px;
}
#nose1{
width: 60px;
height: 60px;
background-color: blueviolet;
position: absolute;
left: 225px;
top: 175px;
}
#nose2{
width: 30px;
height: 30px;
background-color: aqua;
position: absolute;
left: 15px;
top: 15px;
}
</style>
</head>
<body>
<div id="face">
<div id="left"></div>
<div id="right"></div>
<div id="mouse"></div>
<div id="nose1">
<div id="nose2"></div>
</div>
</div>
</body>
</html>
效果如下:
Fighting!