html 位置水平垂直居中,css水平垂直居中有几种实现方式?

项目中经常碰到需要实现水平垂直居中的样式。下面就总结几种常用的方法

5e05b4ce653e3405.jpg

css水平垂直居中有几种实现方式?

1、水平对齐+行高

【思路一】text-align + line-height实现单行文本水平垂直居中

.f10 .test{

text-align: center;

line-height: 100px;

}

测试文字

2、水平+垂直对齐

【思路二】text-align + vertical-align

(相关课程推荐:css视频教程)

【1】在父元素设置text-align和vertical-align,并将父元素设置为table-cell元素,子元素设置为inline-block元素

[注意]若兼容IE7-浏览器,将结构改为

测试文字

【2】若子元素是图像,可不使用table-cell,而是其父元素用行高替代高度,且字体大小设为0。子元素本身设置vertical-align:middle

.f12 .parent{

line-height: 200px;

text-align: center;

font-size:0;

}

.f12 .child{

vertical-align: middle;

}

test

3、margin + vertical-align

要想在父元素中设置vertical-align,须设置为table-cell元素;要想让margin:0 auto实现水平居中的块元素内容撑开宽度,须设置为table元素。而table元素是可以嵌套在tabel-cell元素里面的,就像一个单元格里可以嵌套一个表格

[注意]若兼容IE7-浏览器,需将结构改为

测试文字

4、绝对定位

【1】利用绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto

.f14 .parent{

position: relative;

}

.f14 .child{

position: absolute;

top: 0;

left: 0;

right: 0;

bottom: 0;

height: 50px;

width: 80px;

margin: auto;

}

测试文字

【2】利用绝对定位元素的偏移属性和translate()函数的自身偏移达到水平垂直居中的效果

[注意]IE9-浏览器不支持

.f15 .parent{

position: relative;

}

.f15 .child{

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

}

测试文字

5、flex

[注意]IE9-浏览器不支持

【1】在伸缩项目上使用margin:auto

.f16 .parent{

display: flex;

}

.f16 .child{

margin: auto;

}

测试文字

【2】在伸缩容器上使用主轴对齐justify-content和侧轴对齐align-items

.f17 .parent{

display: flex;

justify-content: center;

align-items: center;

}

测试文字

6、grid

[注意]IE10-浏览器不支持

【1】在网格项目中设置justify-self、align-self或者margin: auto

.f18 .parent{

display: grid;

}

.f18 .child{

align-self: center;

justify-self: center;

}

测试文字

【2】在网格容器上设置justify-items、align-items或justify-content、align-content

.f19 .parent{

display: grid;

/*align-items: center;*/

/*justify-items: center;*/

align-content: center;

justify-content: center;

}

测试文字

本文来自css3答疑栏目,欢迎学习!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值