帝王谷资源网 Design By www.wdxyy.com
在前端开发中,我们经常会遇到各种上不同场景的关于居中的布局,一般水平居中是相对简单,而 垂直居中与水平垂直则相应要麻烦些。在下来我们对各种场景一一列出解决方案。
水平居中
水平居中相对于其它几中居中排列要简单的多,按标签元素可分为行内元素与块级元素居中:
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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
标签:
CSS,居中布局
帝王谷资源网 Design By www.wdxyy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
帝王谷资源网 Design By www.wdxyy.com
暂无评论...
更新日志
2024年10月07日
2024年10月07日
- 班得瑞原装进口《第八张新世纪专辑:琉璃湖畔》1CD[APE/CUE分轨][286.4MB]
- 魏如萱.2011-在哪里(EP)【添翼创越】【WAV+CUE】
- 群星.1981-新金曲奖·青年创作园地12合辑(喜玛拉雅复刻版)【歌林】【WAV+CUE】
- 麦洁文.1989-新曲与精丫新艺宝】【WAV+CUE】
- SNH48《薄荷糖 (Mint Candy)》[320K/MP3][33.72MB]
- SNH48《薄荷糖 (Mint Candy)》[FLAC/分轨][78.59MB]
- 刘美麟《同生》[320K/MP3][70.99MB]
- 群星.1994-宝丽金最流行3CD【宝丽金】【WAV+CUE】
- 群星.2024-聆听“某某”影视原声带【华纳】【FLAC分轨】
- 陈慧娴.1989-永远是你的朋友(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 何洛洛.2024-别叫醒我(EP)【光羽】【FLAC分轨】
- 林忆莲.1996-爱莲说2CD【华纳】【WAV+CUE】
- 黄妃.2005-红【亚律】【WAV+CUE】
- 刘美麟《同生》[FLAC/分轨][161.95MB]
- 群星《前途海量 电影原声专辑》[320K/MP3][106.26MB]