如何用讓嵌套在裏面的div居中
本人是一個前端新手,如何讓兩個相互嵌套的div,讓裏面的div居中是一個比較簡單的問題,面試也常問,我就從其他博客中提取稍微總結一下(轉載侵刪),也加了一點自己的困惑和理解,錯誤的地方希望能有人指出:
- 利用position:absolute的特性
- 設置margin爲auto
- display:table-cell
- transform
- flex
方法一:利用position:absolute的特性
先設置元素的top、left偏離50%,再用margin讓位置往回一半。
.parent{
width: 400px;
height: 400px;
position: relative;
background: red;
}
.child{
width: 200px;
height: 200px;
position: absolute;
background: green;
top: 50%;
bottom: 50%;
margin-left: -100px;
margin-top: -100px;
}
需要注意的是要將父級的postision設爲relative,否則元素將不會相對於父級進行定位
該方法在pc中的兼容性很好,另外,稍微改一下,也就是:
.parent{
width: 400px;
height: 400px;
position: relative;
background: red;
}
.child{
width: 200px;
height: 200px;
position: absolute;
background: green;
top: 50%;
margin-top: -100px;
}
就可以讓div只在垂直方向居中,還是比較常用的
方法二:設置margin爲auto
.parent{
width: 400px;
height: 400px;
position: relative;
background: red;
}
.child{
width: 200px;
height: 200px;
position: absolute;
background: green;
margin: auto;
top: 0;
right:0;
bottom: 0;
top: 0;
}
兼容性:主流瀏覽器都支持,IE6不支持
方法三:display:table-cell
.parent{
width: 400px;
height: 400px;
background: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child{
width: 200px;
height: 200px;
background: green;
display: inline-block;
vertical-align: middle;
}
table-cell屬性是讓標籤元素以表格單元格的形式呈現,類似於td標籤
vertical-align是行內元素的一個屬性,設置行內元素是以基線對齊還是中間對齊
text-align設置後讓元素在水平方位居中
兼容性:由於table-cell是css3的屬性,兼容性上低版本的IE不支持該屬性
方法四:transform
.parent{
width: 400px;
height: 400px;
background: red;
position: relative;
}
.child{
width: 200px;
height: 200px;
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
這邊我有點不太理解的是,我發現並不需要設置position:absolute直接用translate(50%, 50%)也能垂直居中,但網上多數方法都用了position:absolute,希望有大神能夠替我解答下我的疑問
兼容性:IE9以下不支持transform,手機端上的支持比較好
方法五: flex
.parent{
width: 400px;
height: 400px;
background: red;
display: flex;
align-items: center;
justify-content: center;
}
.child{
width: 200px;
height: 200px;
background: green;
}
flex在移動端的支持非常好,在pc端的兼容性還是差了點,所以這種方式是移動端的首選