CSS水平和垂直居中

一、水平居中

1.1 行内元素

.parent{text-align:center}

1.2 块级元素

1.2.1 块级元素一般居中方法

.son{margin:0 auto}

1.2.2 子元素含 float

.parent{width:fit-content;margin:0 auto;}
.son{float:left;}

1.2.3 Flex 弹性盒子

.parent{display:flex;justify-content:center;}

1.2.4 绝对定位

1)transform(绝对定位,left50%,向左平移-50%)

.son{position:absolute;left:50%;transform: translate(-50%,0);}

2)  margin-left(绝对定位,left50%,margin-left:-0.5*子元素宽度)** 注:此方法必须知道子元素宽度**

.son{position:absolute;left:50%;width:200px;margin-left: -100px;}

3)left/right: 0

.son{position:absolute;left:0;right:0;margin:0 atuo;}

二、垂直居中

2.1 行内元素

.parent{height:32px;}
.son{line-height:32px}

注:① 子元素 line-height 值为父元素 height 值。② 单行文本

2.2 块级元素

2.2.1 行内块级元素

.parent::after{display: inline-block;vertical-align: middle;content: '';height:100%;}
.son{display: inline-block;vertical-align: middle;}

2.2.2 table

.parent{display: table;}
.son{display:teble-cell; vertical-align: middle;}

注:IE 6-8不兼容

2.2.3 Flex 弹性盒子

.parent{ display:flex;align-items:center;}

优点: 1、内容块的宽高任意, 优雅的溢出。2、可用于更复杂高级的布局技术中。

缺点:1、IE8/IE9不支持。2、需要浏览器厂商前缀。3、渲染上可能会有一些问题。

2.2.4 绝对定位

1)transform

.parent{position:relative;}
.son{position:absolute;top:50%;transform: translate(0,-50%);}

缺点:IE8不支持, 属性需要追加浏览器厂商前缀, 可能干扰其他 transform 效果, 某些情形下会出现文本或元素边界渲染模糊的现象。

2) margin-top: -0.5*高度

.parent{position:relative;}
.son{position:absolute;top:50%;margin-top:-100px;}

缺点:父元素空间不够时, 子元素可能不可见(当浏览器窗口缩小时,滚动条不出现时).如果子元素设置了overflow:auto, 则高度不够时, 会

出现滚动条。

3)top/bottom: 0;

.parent{position:relative}
.son{position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;}

缺点:没有足够空间时, 子元素会被截断, 但不会有滚动条。

 

参考作者:Agoreal

参考原文:http://www.cnblogs.com/xxcanghai/p/5189353.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值