一、div居中的幾個方法
display:flex 是一種布局方式。它即可以應用於容器中,也可以應用於行內元素。是W3C提出的一種新的方案,可以簡便、完整、響應式地實現各種頁面布局。目前,它已經得到了所有瀏覽器的支持。
Flex是Flexible Box的縮寫,意為"彈性布局",用來為盒狀模型提供最大的靈活性。設為Flex布局以后,子元素的float、clear和vertical-align屬性將失效。
margin 簡寫屬性在一個聲明中設置所有外邊距屬性
彈性布局
1、子div先充滿父元素,在margin:auto,
<style> .container{ height: 600px; width: 600px; border:1px solid black; display: flex; } .box{ width: 200px; height: 100px; background-color: blue; margin: auto; } </style> <div class="container"> <div class="box"></div> </div>
2、彈性布局,通過定義伸縮容器的兩個屬性,justify-content主軸方向,align-items縱軸方向均為center
<style> .container{ height: 600px; width: 600px; border:1px solid black; display: flex; justify-content: center; align-items: center; } .box{ width: 200px; height: 100px; background-color: blue; } </style> <div class="container"> <div class="box"></div> </div>
定位
先相對於父元素margin平移,再回拉法,
<style> .container { height: 600px; width: 600px; border: 1px solid black; position: relative; } .box { width: 300px; height: 300px; background-color: blue; position: absolute; top: 50%; left: 50%; margin-top: -150px; margin-left: -150px;
/* transform: translate(-50%, -50%);*/ } </style>
<style> .container { height: 600px; width: 600px; border: 1px solid black; position: relative; } .box { position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 300px; height: 300px; background-color: blue; margin:auto; } <style>
利用表單單元格td特有屬性,vertical-align,使子div垂直居中,再對子div設置水平居中.
.container{ width: 100px; height: 100px; border: 1px solid blue; /*讓標簽元素以表格單元格形式呈現,類似於td標簽,主要是利用它的特殊屬性: 元素垂直居中對齊,但其會被float、position:absolute、 所以盡量不要與其同用,設置了display:table-cell的元素對寬度高度敏感, 對margin值無反應,所以頁面上出現在了左邊,我就不想再在外面加調了哈, 但會響應padding屬性,基本和td標簽無異*/ display: table-cell;/* 使子div垂直居中 */ vertical-align:middle;/* 再對子div設置水平居中 */ } .box{ width: 50px; height: 50px; background: blue; margin:0 auto; } </style>
二、參考文獻
1、div垂直水平居中的四種方法總結
https://www.cnblogs.com/web-fusheng/p/6724759.html
2、css display:flex 屬性
https://www.jianshu.com/p/d9373a86b748
3、position
https://blog.csdn.net/cx17521000200/article/details/81978651