首页 > IT职业 > IT职场 > css实现水平垂直居中的方法总结
实现水平垂直居中你有多少种方法?这是前端面试必考题啊!-=- 这段时间公司招前端听了一堆五花八门的答案,现在简单总结下!
分两种情况,第一种是,固定宽高在父元素中水平垂直居中,另外一种就是宽高不定的元素在父元素中水平垂直居中,注意第二种其实页适用于宽高固定的情况
公共样式如下:wrap是父级元素,inner是要居中的元素,innerSiz用于定宽高
.wrap { border: 1px solid red; width: 300px; height: 300px;
}.inner { background: green;
}.inner.innerSize{ width: 100px; height: 100px;
}
定宽高的结构如下:
<!-- 定宽高结构 -->我要居中
.wrap{ position: relative;
}.inner{ position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px;
}
.wrap{ position: relative;
}.inner{ position: absolute; top: 0; right: 0; left: 0; bottom: 0; margin: auto;
}
.wrap{ position: relative;
}.inner{ position: absolute; top: calc(50% - 50px); left: calc(50% - 50px);
}
不定宽高的结构如下:
<!-- 定宽高结构 -->我要居中
.wrap{ position: relative;
}.inner{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
}
.wrap{ display: flex; justify-content: center; align-items: center;
}.inner{}
.wrap{ display: table-cell; text-align: center; vertical-align: middle;
}.inner{ display: inline-block;
}
.wrap { display: grid;
}.inner { align-self: center; justify-self: center;
}
方法总结完毕,具体代码地址见:https://github.com/wangchao117/Interview-skills
作者:w如弈如意c
链接:https://www.jianshu.com/p/171325be3714
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3127/viewspace-2814876/ ,如需转载,请注明出处,否则将追究法律责任。