css实现不定宽高元素垂直居中的集中方式

2020-09-02  本文已影响0人  橙色流年

固定高度的垂直居中方式很好处理,但是我们在日常开发中,可能经常会碰到元素高度宽度不固定,但是我们要让他显示在屏幕正中间,比如最常见的弹出层处理,在高度不固定的情况下,如何保证弹出层垂直居中呢?

<style>
.index {
  width: 400px;
  height: 400px;
  background: gray;
  position: relative;
  top: 50%;
  left: 50%;
  margin-top: -200px;
  margin-left: -200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.index-dialog {
  padding: 20px;
  background: red;
  text-align: center;
}
</style>
<div class="index">
  <div class="index-dialog">2222222</div>
</div>

最后效果图如下:


<style>
  .index {
    width: 400px;
    height: 400px;
    background: gray;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -200px;
  }
  .index-dialog {
    position: absolute;
    padding: 20px;
    background: red;
    top: 50%;
    transform: translateY(-50%);
    left: 50%;
    transform: translateX(-50%);
    text-align: center;
  }
</style>
<div class="index">
  <div class="index-dialog">2222222</div>
</div>

最后效果图如下:


通过 display: tabledisplay: table-cell 实现元素垂直居中

<style>
  .index {
    width: 400px;
    height: 400px;
    background: gray;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -200px;
    display: table;
  }
  .index-dialog {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }
</style>
<div class="index">
  <div class="index-dialog">
    <img src="https://upload.jianshu.io/users/upload_avatars/14110538/2f118de3-606c-4da9-bc21-f66931c65792.png?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp" alt="">
  </div>
</div>
<style>
  .index {
    width: 400px;
    height: 400px;
    background: gray;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -200px;
    text-align: center;
  }
  .index::after {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
  }
  .index-dialog {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }
</style>
<div class="index">
  <div class="index-dialog">222</div>
</div>

最后效果图如下:


上一篇下一篇

猜你喜欢

热点阅读