代码:
<p>position左右布局</p>
<div class="container1">
<div class="box1"></div>
<div class="box2"></div>
</div>
.container1, .container2 {
border: 2px solid black;
max-width: 450px;
height: 250px;
margin: 0 auto;
box-sizing: border-box;
position: relative;
}
.container1 .box1 {
width: 200px;
height: 200px;
border: 2px solid red;
position: absolute;
top: 0;
left: 0;
}
.container1 .box2 {
width: 200px;
height: 200px;
border: 2px solid blue;
position: absolute;
top: 0;
right: 0;
}
代码:(使用float必须增加clearfix!使用float必须增加clearfix!使用float必须增加clearfix!)
<p>float左右布局</p>
<div class="container2 clearfix">
<div class="box3"></div>
<div class="box4"></div>
</div>
.clearfix::after {
content: '';
display: block;
clear: both;
}
.container2 .box3 {
width: 200px;
height: 200px;
border: 2px solid red;
float: left;
}
.container2 .box4 {
width: 200px;
height: 200px;
border: 2px solid blue;
float: right;
}
<p>position左中右布局</p>
<div class="container3">
<div class="box5"></div>
<div class="box6"></div>
<div class="box7"></div>
</div>
.container3 {
border: 2px solid black;
max-width: 700px;
height: 300px;
margin: 0 auto;
position: relative;
}
.container3 .box5 {
width: 200px;
height: 200px;
border: 2px solid red;
position: absolute;
top: 0;
left: 0;
}
.container3 .box6 {
width: 200px;
height: 200px;
border: 2px solid yellow;
position: absolute;
top: 0;
left: 250px;
}
.container3 .box7 {
width: 200px;
height: 200px;
border: 2px solid green;
position: absolute;
top: 0;
right: 0;
}
<p>flex水平垂直居中</p>
<div class="container4">
<div class="box8"></div>
</div>
.container4 {
border: 2px solid black;
max-width: 450px;
height: 250px;
margin: 0 auto;
display: flex;
align-items: center;
}
.container4 .box8 {
width: 200px;
height: 200px;
border: 2px solid red;
margin: 0 auto;
}
水平居中
行内元素liline
p {
text-align: center;
}
块级元素block
div {
margin: 0 auto;
}
多块级元素block
对其父级元素设置text-align: center;然后子级元素display: inline-block;
或者使用flex布局
垂直居中
行内元素inline
单行:设置上下相等的paddding,或者设置line-height
多行:设置上下相等的paddding,或者vertical-align:middle;;或者使用flex布局
块级元素block
flex布局