方法1:每个div的css样式里都加上 float:left; / float:right;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
height: 100px;
width: 100px;
background-color: palevioletred;
float: left;
}
.box2 {
height: 100px;
width: 100px;
background-color: skyblue;
float: left;
}
.box3 {
height: 100px;
width: 100px;
background-color: orange;
float: left;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>
</html>
方法2: 每个div的css样式里都加上 display:inline-block;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
height: 100px;
width: 100px;
background-color: palevioletred;
display:inline-block;
}
.box2 {
height: 100px;
width: 100px;
background-color: skyblue;
display:inline-block;
}
.box3 {
height: 100px;
width: 100px;
background-color: orange;
display:inline-block;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>
</html>
用这种方法有一定的缺陷,div之间会存在间隙。
解决办法:设置父元素 display: table; border-spacing: 0;间隙就消失了
.box {
display: table;
border-spacing: 0;
}
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
方法3:flex布局 父元素display: flex; 子元素flex: 1; 这里注意父元素要设定盒子宽度等于所有子元素盒子宽度之和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
display: flex;
width: 300px;
}
.box1 {
height: 100px;
width: 100px;
background-color: palevioletred;
flex: 1;
}
.box2 {
height: 100px;
width: 100px;
background-color: skyblue;
flex: 1;
}
.box3 {
height: 100px;
width: 100px;
background-color: orange;
flex: 1;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>
方法4:绝对定位 父绝子相 ,从而达到绝对定位的目的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: relative;
width: 300px;
}
.box1 {
height: 100px;
width: 100px;
background-color: palevioletred;
position: absolute;
left: 0;
}
.box2 {
height: 100px;
width: 100px;
background-color: skyblue;
position: absolute;
left: 100px;
}
.box3 {
height: 100px;
width: 100px;
background-color: orange;
position: absolute;
left: 200px;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>