HTML代碼
<div class="father">
<div class="son"></div>
</div>
CSS代碼
.father {
width: 500px;
height: 300px;
background-color: lightskyblue;
}
.son {
width: 100px;
height: 100px;
background-color: lightgreen;
}
初始效果
初始效果
以下代碼都是基于上面代碼添加
A => 水平居中
效果預覽
- flex方式
.father {
display: flex;
justify-content: center;
}
- 定位 + left方式(已知寬度可以用margin-left, 未知寬度用transform)
.father {
position: relative; /*想知道為什么加這一句,去掉看son對誰居中就知道了*/
}
.son {
position: absolute;
left: 50%;
margin-left: -50px; /* 已知寬度 */
/*transform: translateX(-50%);/* 未知寬度盏混,這里的50%是參考自身實際寬度 */
}
- margin auto方式
.son {
margin: 0 auto;
}
B => 垂直居中
效果預覽
- flex方式
.father {
display: flex;
align-items: center;
}
- 定位 + top方式(已知惜论、未知寬度同理)
.father {
position: relative;
}
.son {
position: absolute;
top: 50%;
margin-top: -50px;
/*transform: translateY(-50%);*/
}
- table-cell + vertical-align方式
.father {
display: table-cell;
vertical-align: middle;
}
C => 水平垂直居中
效果預覽
- flex方式
.father {
display: flex;
justify-content: center;
align-items: center;
}
- 定位 + top left方式(已知馆类、未知寬度同理)
.father {
position: relative;
}
.son {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
/*transform: translate(-50%,-50%);*/
}
- table-cell + vertical-align + margin auto方式
.father {
display: table-cell;
vertical-align: middle;
}
.son {
margin: auto;
}
吃完東西擦嘴,學完東西總結(jié)
如果不考慮兼容性句喜,那就用flex吧沟于,其次,定位的方式也常用旷太,table-cell比較冷門,多一條后路
跟我念:flex存崖、定位、table-cell ... flex来惧、定位吕嘀、table-cell
什么贞瞒?不夠趁曼,那繼續(xù)看這個吧
>> 何居中一個元素(終結(jié)版)