容器box內的居中:
公共部分css和html結構
<!-- CSS -->
.box{
width: 200px;
height: 200px;
border: 1px solid #eee;
box-sizing: border-box;
font-size: 0;
}
.box div{
width: 50px;
height: 50px;
background: #00cc00;
}
<!-- html布局 -->
<div class="box box1">
<div></div>
</div>
<!-- 行內塊法第二種方案的html -->
<div class="box box3">
<span class="con"></span>
<div></div>
</div>
- 添加font-size:0主要是子元素是inline-block 元素時部分瀏覽器會對換行和空格產生一個“字符”做處理。
表格布局法
利用display:table-cell結合vertial-align:middle方法來實現垂直居中
.box{
display: table-cell;
vertical-align: middle;
}
.box div{
margin: 0 auto;
}
行內塊法
1.利用display: inline-block;結合vertial-align:middle;方法來實現垂直居中,父級元素的line-height需要設置為父級元素本身的高度。
.box{
line-height: 200px;
font-size: 0;
text-align: center;
}
.box div{
display: inline-block;
vertical-align: middle;
}
2.原理同上,需新增一個空的span元素并將其height設為100%,
.box{
text-align: center;
}
.box div{
display: inline-block;
vertical-align: middle;
}
.box .con{
display: inline-block;
width: 0;
height: 100%;
overflow: hidden;
margin-left: -1px;
font-size: 0;
line-height: 0;
vertical-align: middle;
}
flex布局
利用flex布局
1.父級align-items: center;justify-content: center;
2.子元素設置align-self: center;
3.子元素設置margin: auto;
.box{
display: flex;
align-items: center;
justify-content: center;
}
.box{
display: flex;
justify-content: center;
}
.box div{
align-self: center;
}
.box{
display: flex;
}
.box div{
margin: auto;
}
絕對定位
先把元素的左上角放置在(最近的具有定位屬性的祖先元素)視窗的正中心,然后利用負外邊距(或translate() 變形函數)把它向左、向上移動(移動距離相當于它自身寬高的一半),從而把元素的正中心放置在窗口的正中心
子元素不固寬高:
.box div{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
子元素固定寬高:
.box div{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
子元素固定寬高:
position:absolute;
top: calc(50% - 3em);
left: calc(50% - 9em);
width: 18em;
height: 6em;
視窗中居中
width: 18em;
padding: 1em 1.5em;
margin: 50vh auto 0;
transform: translateY(-50%);