博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
面试--css实现元素的水平和垂直居中
阅读量:6972 次
发布时间:2019-06-27

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

针对单行文本

使用line-height

.wrap{        width: 200px;height: 200px;background: yellow;    }    .wrap span{        line-height: 200px ;text-align: center;    }
sasas

针对已知高度的块级元素

相对+绝对+margin-top:-height/2+margin-left:-width:-width/2

针对行内块元素实现处置居中

.wrap{        width: 200px;height: 200px;background: yellow;    }    .wrap img{        vertical-align:middle;text-align: center;    }    .wrap .block{        height: 100%;width: 0;    }

vertical-align:vertical 属性是针对兄弟级别的元素设置的

其中.block也可以使用 img:after或者:before来代替

针对父元素和子元素的高度都未知情况下 定位+transform

.wrap{        width: 200px;height: 400px;background: yellow;position: relative;    }    .wrap div{        position: absolute;        top:50%;left: 50%;transform: translate(-50%,-50%);background: red;    }

sasas

sasas

sasas

sasas

针对父元素和子元素的高度都未知情况下 父:text-align:center+表格布局 子:vertical-align:middle+表格布局

.wrap{        width: 200px;height: 400px;background: yellow;display: table;text-align: center;    }    .wrap div{        display: table-cell;vertical-align:middle;    }    

sasas

sasas

sasas

sasas

针对父元素高度但是子元素的高度已知都未知情况下 父:相对定位 子:绝对定位+四个属性都为0 +margin:auto

.wrap{        width: 200px;height: 400px;background: yellow;        position: relative;    }    .wrap div{        width:20px;height:100px;position: absolute;top:0;left: 0;right: 0;bottom: 0;margin: auto;        background: red;    }    

sasas

sasas

sasas

sasas

使用flex布局

.wrap{        width: 200px;height: 400px;background: yellow;        position: relative;        display: flex; justify-content: center; flex-direction: column;    }    .wrap div{        width:20px;top:0;left: 0;right: 0;bottom: 0;margin: auto;        background: red;    }    

sasas

sasas

sasas

sasas

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

你可能感兴趣的文章
linux tmux 简单操作
查看>>
【状压dp】AC Challenge
查看>>
Oracle Install
查看>>
错误记录 "MongoClient opened before fork. Create MongoClient "
查看>>
第十二次作业
查看>>
第136天:Web前端面试题总结(理论)
查看>>
iOS开发-模板方法模式
查看>>
算法-最大连续子序列和
查看>>
NodeJS之Mac初体验
查看>>
勾股数
查看>>
zoj 1597 Circular Area
查看>>
v-solt插槽
查看>>
OCM_第六天课程:Section3 —》数据库可用性
查看>>
ORA-00257 archiver error. 错误的处理方法
查看>>
开发Servlet的方法(2)
查看>>
Apache mod_wsgi部署Django项目
查看>>
玲珑杯#20 C 漆黑的太阳——莫队
查看>>
MySQL数据库建立外键失败的原因总结
查看>>
网络资源收集工具编码规范
查看>>
ZOJ3778 Talented Chef(贪心)
查看>>