ITPub博客

首页 > IT职业 > IT职场 > css实现水平垂直居中的方法总结

css实现水平垂直居中的方法总结

IT职场 作者:shinez 时间:2021-09-09 09:59:57 0 删除 编辑

css实现水平垂直居中的方法总结

实现水平垂直居中你有多少种方法?这是前端面试必考题啊!-=- 这段时间公司招前端听了一堆五花八门的答案,现在简单总结下!
分两种情况,第一种是,固定宽高在父元素中水平垂直居中,另外一种就是宽高不定的元素在父元素中水平垂直居中,注意第二种其实页适用于宽高固定的情况

公共样式如下:wrap是父级元素,inner是要居中的元素,innerSiz用于定宽高

.wrap {    border: 1px solid red;    width: 300px;    height: 300px;
}.inner {    background: green;
}.inner.innerSize{    width: 100px;    height: 100px;
}
元素固定宽高

定宽高的结构如下:

<!-- 定宽高结构 -->
    
我要居中
方法一:position + 上下margin负自身宽高的一半
.wrap{    position: relative;
}.inner{    position: absolute;    top: 50%;    left: 50%;    margin-top: -50px;    margin-left: -50px;
}
方法二:position + margin:auto
.wrap{    position: relative;
}.inner{    position: absolute;    top: 0;    right: 0;    left: 0;    bottom: 0;    margin: auto;
}
方法三:position + calc
.wrap{    position: relative;
}.inner{    position: absolute;    top: calc(50% - 50px);    left: calc(50% - 50px);
}
元素不定宽高的情况(也适用于固定宽高的情况)

不定宽高的结构如下:

<!-- 定宽高结构 -->
    
我要居中
方法一:position + transform
.wrap{    position: relative;
}.inner{    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);
}
方法二:flex
.wrap{    display: flex;    justify-content: center;    align-items: center;
}.inner{}
方法三:table
.wrap{    display: table-cell;    text-align: center;    vertical-align: middle;
}.inner{    display: inline-block;
}
方法三:gird布局
.wrap {    display: grid;
}.inner {    align-self: center;    justify-self: center;
}



作者:w如弈如意c
链接:https://www.jianshu.com/p/171325be3714


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3127/viewspace-2814876/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    0
  • 访问量
    932