水平居中
1辛友、內(nèi)聯(lián)元素居中:父元素設(shè)置text-align:center
<div>hello world<div>
div{
text-align:center;
}
2办陷、塊級(jí)元素居中:該元素設(shè)置margin-left:auto;margin-right:auto
<div class="parent">
<div class="child"></div>
<div>
.parent{
height:100px;
background:red;
}
.child{
height:50px;
width:40px;
background:green;
margin-left:auto;
margin-right:auto;
}
垂直居中
塊級(jí)元素居中:
方法一:不設(shè)置.parent的height膨报,設(shè)置.parent{padding:10px 0}
<div class="parent">
<div class="child"></div>
<div>
.parent{
padding:10px 0;
background:red;
}
.child{
height:50px;
width:40px;
background:green;
margin-left:auto;
margin-right:auto;
}
方法二:設(shè)置.parent的height瞳步,通過(guò)postion absoulte margin auto
實(shí)現(xiàn)
<div class="parent">
<div class="child"></div>
<div>
.parent{
height:600px;
background:red;
position:relative;
}
.child{
background:green;
position:absolute;
width:300px;
height:300px;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
方法三:設(shè)置.parent的height抠璃,通過(guò)postion absolute margin 負(fù)值
實(shí)現(xiàn)
<div id="parent">
<div id="child"></div>
<div>
.parent{
height:600px;
background:red;
position:relative;
}
.child{
background:green;
position:absolute;
width:300px;
height:300px;
top:50%;
left:50%;
margin-left:-150px;
margin-top:-150px;
}
方法四:設(shè)置.parent的height术奖,通過(guò)transform: translate(-50%,-50%);
實(shí)現(xiàn)
translate(x,y) 括號(hào)的百分比數(shù)據(jù)礁遵,會(huì)以本身的長(zhǎng)寬做參考,比如采记,本身的長(zhǎng)為100px佣耐,高為100px. 那填(50%,50%)就是向右,向下移動(dòng)50px唧龄,添加負(fù)號(hào)就是向著相反的方向移動(dòng)
<div class="parent">
<div class="child">
</div>
<div>
.parent{
height:600px;
background:red;
position:relative;
}
.child{
background:green;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
方法五:通過(guò)flex
實(shí)現(xiàn)
<div class="parent">
<div class="child"></div>
<div>
.parent{
background:red;
height:600px;
display: flex;
justify-content: center;//justify-content屬性定義了項(xiàng)目在主軸上的對(duì)齊方式兼砖。
align-items: center; //align-items屬性定義項(xiàng)目在交叉軸上如何對(duì)齊。
}
.child{
background:green;
width:300px;
height:200px;
}
常用屬性
transform
translate(x,y)
scale(x,y)
rotate(angle)
display:flex
justify-content:center//屬性定義了項(xiàng)目在主軸上的對(duì)齊方式既棺。
align-items:center//屬性定義項(xiàng)目在交叉軸上如何對(duì)齊讽挟。