做一个水平和垂直居中的模态弹框这么一个小需求,对于我们这些前端来说,应该是常事。
在css3出来以前,我们要想让元素既水平居中又要垂直居中只有一个办法(我能想到的),就是通过js计算,把它们定位到屏幕中间位置。这方法比较笨,也麻烦。
下面两种方式,可以让元素快速定位到屏幕中间。
flex布局
- .flex-mask { display: flex; position: fixed; z-index: 1; top: 0; left: 0; bottom: 0; right: 0; align-items: center; // 垂直居中 justify-content: center; // 水平居中 background: rgba(0,0,0,.5); } .flex-box { width: 500px; height: 300px; background-color: #fff; border-radius: 10px; }
登录后复制
使用translate
- .transform-box { position: fixed; z-index: 2; top: 50%; left: 50%; width: 300px; height: 150px; background-color: red; border-radius: 10px; transform: translate(-50%, -50%); }
登录后复制
以上就是设置元素水平、垂直居中有哪两种方式 的详细内容,更多请关注【创想鸟】其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。