先給出HTML結構佈局
<div class="par"> <div class="child">我是子元素</div> </div>
.par{ text-align: center; } .child{ background-color: tomato; display:inline-block; }
將子元素設置爲inline-block
這樣既能夠像塊元素同樣設置盒模型,又能夠像行內元素同樣試用text-align:center
進行居中flex
將子元素設置爲inline-block
後,子元素爲塊級元素,寬度爲內容寬度code
.par{ } .child{ background-color: tomato; display:table; margin:0 auto; }
table
元素是塊級元素,寬度自適應爲內容寬度,因此經過display:table
對子元素進行轉換並設置塊元素居中標配margin:0 auto
orm
.par{ position: relative; } .child{ background-color: tomato; width:300px; position: absolute; left:50%; transform: translateX(-50%); }
因爲子元素是個塊級元素(div),默認佔滿父元素寬度,因此咱們將子元素寬度設爲300pxit
原理很簡單,先用絕對定位將子元素置於距父元素左邊界一半的位置,而後再將子元素向左移動自身的一半,達到居中效果io
注意,position:relative
將父元素設爲子元素絕對定位的參照物table
.par{ display:flex; justify-content: center; } .child{ background-color: tomato; }
因爲flex-grow
屬性默認值爲0,flex-basis
屬性默認值爲auto,因此寬度爲內容寬度(在沒有設置指定值時,不然爲指定值)form
順便說一句,flex很強大class
高度爲元素高度,就不指定具體值了原理
.par{ height:500px; display:table-cell; vertical-align:middle; } .child{ background-color: tomato; }
子元素寬度爲內容寬度,父元素寬度爲子元素寬度
.par{ height:500px; position: absolute; } .child{ background-color: tomato; width:300px; position: absolute; top:50%; transform: translateY(-50%); }
不指定子元素寬度的話,子元素的內容將縱向展現
.par{ height:500px; display:flex; align-items:center; } .child{ background-color: tomato; width:300px; }
上述兩種居中佈局的結合
.par{ width:500px; height:500px; border:1px solid #ccc; text-align: center; display: table-cell; vertical-align: middle; } .child{ background-color: tomato; width:300px; display:inline-block; }
.par{ width:500px; height:500px; border:1px solid #ccc; position: relative; } .child{ background-color: tomato; width:300px; position: absolute; left:50%; top:50%; transform: translate(-50%,-50%); }
.par{ width:500px; height:500px; border:1px solid #ccc; display:flex; justify-content: center; align-items: center; } .child{ background-color: tomato; width:300px; }
有問題歡迎提問,實踐出真知