这是一个超详细的 CSS 实现居中定位弹窗效果源码解析,如果看完这篇文章还没学明白,小编劝你趁年轻赶紧改行!
弹窗一般有两种情况:
弹窗的尺寸是已知的(宽高都是固定的);弹窗尺寸是未知的(内容不固定,弹窗高度随内容改变);
本篇文章会对这两种情况,各给出2种解决方法。每一种方法的实现源码解释都超详细!!
一、固定尺寸弹窗
方案一(定位+外边距取反):
.popup{
background-color: rgba(255, 0, 0, 0.35);
width: 300px;
height: 260px;
position: fixed;
/* 设置 top 和 left 为 50%,使弹窗的元素左上角在窗口的中心点 */
top: 50%;
left: 50%;
/* 通过 margin 的 上外边 和 左外边的值为 元素尺寸的 -50% 时,刚好让元素偏移位置窗口的中间 */
margin: -130px 0 0 -150px;
}
弹窗
河浪 1846492969
方案二(定位+外边距 auto):
.popup{
background-color: rgba(255, 0, 0, 0.35);
width: 300px;
height: 260px;
position: fixed;
/* 上下左右4个方向的定位都设置为0 */
top: 0;
left:0;
right: 0;
bottom: 0;
/* 外边距全设置为 auto ,元素就这么神奇的居中定位了 */
margin: auto;
}
弹窗
河浪 1846492969
二、非固定尺寸弹窗
非固定尺寸的弹窗的实现办法都是需要先实现一个可以让直接子元素居中的容器
方案一(行高+行块元素):
/* 这是一个弹窗的容器 */
.popup{
width: 100vw;
height: 100vh;
position: fixed;
/* 上下左右4个方向的定位都设置为0 */
top: 0;
left:0;
/* 设置内容居中 */
text-align: center;
/* 行高为窗口的高度,行高属性是不能使用百分比的 */
line-height: 100vh;
}
/* 弹窗内容容器 */
.popup-content{
background-color: rgba(255, 0, 0, 0.35);
padding: 16px;
/* 设置为行块,父级的 text-align 和 line-height 对块元素是不能做定位的 */
display:inline-block;
/* 当前内容容器元素以 文字基线 居中对齐 */
vertical-align: middle;
/* 设置内容中的行高为默认,用来覆盖父元素的 100vh 值 */
line-height: normal;
}
弹窗
河浪 1846492969
方案二(flex):
/* 这是一个弹窗的容器 */
.popup{
width: 100vw;
height: 100vh;
position: fixed;
/* 上左2个方向的定位都设置为0 */
top: 0;
left:0;
/* 使用 flex 布局 */
display: flex;
flex-direction: row;
flex-wrap: nowrap;
/* 项目在主轴对齐方式为居中 */
justify-content: center;
/* 项目在交叉轴对齐方式为居中 */
align-items: center;
align-content: center;
}
/* 弹窗内容容器 */
.popup-content{
background-color: rgba(255, 0, 0, 0.35);
padding: 16px;
}
弹窗
河浪 1846492969
随着CSS版本的更新,现代浏览器的兼容越来越好。flex的出现使得原来的痛点都得到了解决,小编也有3年时间没有做过兼容IE8的项目了。在条件允许的情况下,推荐大家使用 flex 的方式,简单又通用!
最后,希望大家不要写出下面示例的CSS代码。拿个动画属性写布局,只能说NB!
作者:黄河爱浪
本文原创,著作权归作者所有,转载请注明原链接及出处