CSS(层叠样式表)是一种用于描述 HTML 或 XML 文档样式的样式表语言。通过 CSS,可以控制网页中元素的位置、布局、颜色、字体等样式。
float
属性将元素浮动到指定位置。position
属性(如 static
、relative
、absolute
、fixed
)对元素进行绝对或相对定位。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>普通流布局示例</title>
<style>
.container {
width: 300px;
border: 1px solid black;
}
.box {
width: 100px;
height: 100px;
background-color: red;
margin: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>浮动布局示例</title>
<style>
.container {
width: 300px;
border: 1px solid black;
}
.box {
width: 100px;
height: 100px;
background-color: red;
float: left;
margin: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位布局示例</title>
<style>
.container {
width: 300px;
height: 300px;
border: 1px solid black;
position: relative;
}
.box {
width: 100px;
height: 100px;
background-color: red;
}
.box1 {
position: absolute;
top: 10px;
left: 10px;
}
.box2 {
position: absolute;
top: 10px;
right: 10px;
}
.box3 {
position: absolute;
bottom: 10px;
left: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
</div>
</body>
</html>
原因:浮动元素脱离普通流,导致父元素无法正确计算高度。
解决方法:
.container {
overflow: auto; /* 或者使用 clearfix 技巧 */
}
原因:绝对定位元素不受父元素边界限制。
解决方法:
.container {
position: relative;
}
.box {
position: absolute;
top: 10px;
left: 10px;
}
通过以上内容,你应该对 CSS 控制 div 位置有了全面的了解,并能解决常见的布局问题。
领取专属 10元无门槛券
手把手带您无忧上云