面试中经常被问到css的五种水平垂直居中方法

<html>

<div class="box"><img></div>

<css>

一/*定位和需要定位的元素的margin减去宽高的一半*/

.box{width:300px;height:300px;background:#000;border:1px solid red;position:relative;}

.box img{width:100px;height:150px;position:absolute;top:50%;left:50%;margin-top:-75px;margin-left:-50px;}

二/*定位和margin:auto*/

.box{width:300px;height:300px;background:#000;border:1px solid red;position:relative;}

.box img{width:100px;height:100px;position:absolute;top:0;left:0;right:0;bottom:0;margin:auto;}

三/*绝对定位和transfrom*/

.box{width:300px;height:300px;background:#000;border:1px solid red;position:relative;}

.box img{width:100px;height:100px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}

四/*display:table-cell*/

.box{width:300px;height:300px;background:#000;border:1px solid red;display:table-cell;vertical-align:middle;text-align:center;}

.box img{width:100px;height:150px;}

五/*flexbox居中*/

.box{width:300px;height:300px;background:#000;border:1px solid red;display:flex;justify-content:center;align-items:center;}

.box img{width:150px;height:100px;}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、垂直对齐 如果你用CSS,则你会有困惑:我该怎么垂直对齐容器中的元素?现在,利用CSS3的Transform,...
    kiddings阅读 3,213评论 0 11
  • 各种纯css图标 CSS3可以实现很多漂亮的图形,我收集了32种图形,在下面列出。直接用CSS3画出这些图形,要比...
    剑残阅读 9,715评论 0 8
  • H5移动端知识点总结 阅读目录 移动开发基本知识点 calc基本用法 box-sizing的理解及使用 理解dis...
    Mx勇阅读 4,650评论 0 26
  • 移动开发基本知识点 一.使用rem作为单位 html { font-size: 100px; } @media(m...
    横冲直撞666阅读 3,529评论 0 6
  • 文章总结来自知乎圆桌 Hi 职场 《工作中,需要其他部门提供支持常常会被拖延,要怎么办?》@邀明月 总结以下,与其...
    onetwo3go阅读 360评论 0 0