在前端開發中,我們經常會遇到各種上不同場景的關于居中的布局,一般水平居中是相對簡單,而 垂直居中與水平垂直則相應要麻煩些。在下來我們對各種場景一一列出解決方案。
水平居中
水平居中相對于其它幾中居中排列要簡單的多,按標簽元素可分為行內元素與塊級元素居中:
1、行內元素
如:a img span em b small 此類標簽元素及文本
.center { text-align: center; }2、塊級元素
如:div section header p此類標簽元素,需要設置寬度
.center { margin: 0 auto; }垂直居中
1、line-height
針對有且僅有一行內容時可行。將line-height值設為相對應高度即可。
2、vertical-align
針對行內元素如img span等元素,其對齊相對于文本基線。達不到完美的垂直居中,不常用。
3、其它
關于垂直居中其它方式參考水平垂直居中。
水平垂直居中
在水平垂直居中的場景中,可分為定寬定高、不定寬不定高,按不同應用場景可分如下幾種方式,在布局中實際情況而定。
1、Flex方式
適用場景:IE9+、現代瀏覽器、響應式、不定寬不定高
<section class="center"> <div>水平垂直居中</div></section>.center { display: flex; justify-content: center; align-items: center;}2、絕對定位方式
適用場景:IE8+、及現代瀏覽器、響應式
<section class="center"> 水平垂直居中</section>.center { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto;}3、絕對定位+transform方式
適用場景:IE9+、及現代瀏覽器、響應式、不定寬不定高
<section class="center"> 水平垂直居中</section>.center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%)}4、絕對定位+calc函數
適用場景:IE9+、及現代瀏覽器、定寬定高
<section class="center"> 水平垂直居中</section>.center { width: 200px; height: 200px; position: absolute; top: calc(50% - 100px); left: calc(50% - 100px); }5、絕對定位+margin負屬性
適用場景:IE6+、及現代瀏覽器、定寬定高
<section class="center"> 水平垂直居中</section>.center { position: absolute; top: 50%; left: 50%; width: 200px; height: 200px; margin-left: -100px; margin-top: -100px;}6、Table-cell方式
適用場景:IE8+、及現代瀏覽器、不定寬不定高
<div class="table"> <div class="table-cell"> <div class="center-content"> 水垂直居中 </div> </div></div>.table{ display: table; }.table-cell { display: table-cell; vertical-align: middle; text-align: center;}.center-content{ width: 50%; margin: 0 auto;}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答