css实现弹窗效果(背景透明+居中)

370 阅读1分钟
  • 分两种模式:固定尺寸(宽高固定)与非固定尺寸(宽高不固定)

  • 固定尺寸:

    方式一:固定定位 + 负外边距实现居中

     <div class="div">
        <h1>弹窗</h1>
        <h2>固定宽高</h2>
      </div>
      
      css代码:
    .div {
      background-color: rgba(22, 0, 0, 0.05); //通过rgba设置透明度
      width: 300px;
      height: 260px;
      position: fixed; // 固定定位
      top: 50%;
      left: 50%;
      margin: -130px 0 0 -150px; 
    } 
      

方式二:固定定位 + 负外边距实现居中

 <div class="div">
        <h1>弹窗</h1>
        <h2>固定宽高</h2>
      </div>
      
      css代码
    div {
      background-color: rgba(147, 142, 142, 0.05);
      width: 300px;
      height: 260px;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
     }
  • 非固定尺寸:

方式一:固定定位 + 行高 + 块级元素

这里需要一个父级div充当全屏效果
<div class="div">
    <div class="divSon">
      <h1>弹窗</h1>
      <h2>非固定</h2>
    </div>
  </div> 
  
  css代码:
 .div {
  height: 100vh;
  width: 100vw;
  position: fixed;
  left: 0;
  top: 0;
  text-align: center;
  line-height: 100vh
}

.divSon {
  background-color: rgba(147, 142, 142, 0.05);
  padding: 10px;
  display: inline-block;
  vertical-align: middle;
  line-height: normal; // 替换父元素中的行高
}

方式二:最优方式 采用弹性布局进行实现

.div {
      height: 100vh;
      width: 100vw;
      position: fixed;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
    } 

      .divSon {
      width: 500px;
      background-color: rgba(147, 142, 142, 0.05);
      padding: 10px;
    }