盒子垂直和水平方向居中的几种方式
设宽高
- 第一种方法:设宽高,外边距给盒子宽高一半的负值
<div class="box_center"></div>
.box_center{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
- 设宽高,给盒子定位,上下左右都为0
<div class="box_two"></div>
.box_two{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
margin: auto;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
}
不定宽高
- 第一种
<div class="box_three">
<div class="img"></div>
</div>
*{
margin: 0px;
padding: 0px;
list-style-type: none;
}
html,body{
height: 100%;
overflow: hidden;
}
.box_three{
width: 100%;
height: 100%;
background-color: skyblue;
display: flex;
}
.img{
margin: auto;
width: 200px;
height: 200px;
- 第二种:弹性盒子
<div class="box">
<div class="child">child</div>
</div>
.box{
height:500px;
display:flex;
display:flex;
align-items:center;
align-items:center;
justify-content:center;
justify-content:center;
border:1px solid #ccc;
}
div.child{
width:200px;
height:200px;
background-color:red;
}
- 第三种table-cell
<div class="table-cell">
<p>哈哈哈</p>
</div>
.table-cell {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
border:1px solid #666;
}
- 第四种
<div class="box">
<div></div>
</div>
.box{
height:600px;
display:flex;
justify-content:center;
align-items:center;
}
.box>div{
background: green;
width: 200px;
height: 200px;
}
扇形
<div class="sector"></div>
.sector {
width: 0;
height: 0;
border-width: 50px;
border-style: solid;
border-color: #f00 transparent transparent;
border-radius: 50px;
}
/* border-color的颜色旋转方向是顺时针方向旋转,设置四个边框的颜色,
有四个值时上、右、下、左
有三个值时:上、右左、下
border-color:dotted red green;上下为红色,左右为green*/