博客
关于我
css 各种居中方法总结
阅读量:465 次
发布时间:2019-03-06

本文共 1389 字,大约阅读时间需要 4 分钟。

转:

前言

在使用 css 设置页面样式时会经常遇到需要居中的情况,下面我总结了一些 css 在不同条件下实现居中的方法。有一些方法具有一些 hack 味道,大家看看就好。

为了方便显示居中效果,给父元素和子元素都设置了边框和背景样式,由于效果都差不多,对于每一个方法我就不截图显示了,水平居中的大概实现是这样的
如果要看每一个方法的具体表现,可以查看标题后的在线例子

1、水平居中 + block 子元素定宽 + margin 在线例子

children 子元素

2、水平居中 + inline-block 子元素不定宽 + text-align 在线例子

children 子元素

3、水平居中 + inline-block 子元素定宽 + text-align 在线例子

children 子元素

4、水平居中 + inline 子元素不定宽 + text-align 在线例子

inline 类型的元素设置高宽是无效的,因此也没有定不定宽的说法,这里写上是为了看起来一致

children 子元素

5、水平垂直居中 + flex + 子元素不定宽高 在线例子

children 子元素

6、水平垂直居中 + flex + 子元素不定宽高 + margin 在线例子

children 子元素

7、水平垂直居中 + gird + 子元素不定宽高 在线例子

children 子元素

8、水平垂直居中 + gird + 子元素不定宽高(居中属性设置在子元素上) 在线例子

children 子元素

9、水平垂直居中 + gird + 子元素不定宽高 + margin 在线例子

children 子元素

10、水平垂直居中 + absolute + 子元素定宽高 + margin 在线例子

children 子元素

11、水平垂直居中 + absolute + 子元素不定宽高 + margin 在线例子

fit-content 这属性具有兼容问题

children 子元素

12、水平垂直居中 + absolute + 子元素不定宽高 + transform 在线例子

children 子元素

13、水平垂直居中 + table-cell + 子元素不定宽高 + text-align + vertical-align 在线例子

children 子元素

14、水平垂直居中 + inline/inline-block 子元素不定宽高 + vertical-align 在线例子

children 子元素

15、水平垂直居中 + writing-mode + inline/inline-block 子元素不定宽高 + text-align 在线例子

这个方法受默认排版影响,也是有兼容问题的

children 子元素

16、水平垂直居中 + 水平垂直居中 + block 子元素定宽 + 父元素高度由子元素决定 + padding/margin 在线例子

children 子元素

17、水平垂直居中 + 子元素不定宽高 + 父元素高度由子元素决定 + line-height 在线例子

children 子元素

18、正方形十字居中 在线例子

总结

主要总结了一些日常遇到的 css 居中方法,其中列举的方法也可以组合使用,如果你有其他居中例子,欢迎留言分享

转:

转载地址:http://lzkbz.baihongyu.com/

你可能感兴趣的文章
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>