在前端开发中,我们经常会遇到各种上不同场景的关于居中的布局,一般水平居中是相对简单,而 垂直居中与水平垂直则相应要麻烦些。在下来我们对各种场景一一列出解决方案。
水平居中
水平居中相对于其它几中居中排列要简单的多,按标签元素可分为行内元素与块级元素居中:
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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 范文芳.1996-FNNTASY【HYPE】【WAV+CUE】
- 纯音入心系列纯音乐《韵味古筝曲》1CD[MP3][146.2MB]
- 纯音入心系列纯音乐《古筝系列-传统乐曲》1CD[MP3][974.7MB]
- 纯音入心系列纯音乐《古筝系列-弦凝指咽声停处》1CD[MP3][656.5MB]
- 群星.1994-大烂片2辑【派森】【WAV+CUE】
- 吴倩莲.1997-望爱【EMI百代】【WAV+CUE】
- 杨千嬅.2002-万紫千红演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郭采洁.2015-Begin.Again爱造飞鸡【华纳】【FLAC分轨】
- 许志安.2011-ON.AND.ON【东亚】【WAV+CUE】
- 潘秀琼.1994-木兰从军【名将】【WAV+CUE】
- 纯音入心系列纯音乐《古筝系列-当流行乐遇到古筝》1CD[MP3][1.9GB]
- 纯音入心系列纯音乐《精选古筝名曲100首》1CD[MP3][388.7MB]
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]