关于css:实现已知或者未知高度div居中

6次阅读

共计 967 个字符,预计需要花费 3 分钟才能阅读完成。

// 第一种办法
<div class="box1">
    <div class="inner"></div>
</div>
<style>
    .box1{
      position:relative;
      height:100vh;
    }
    .inner{
      position:absolute;
      top:50%;
      left:50%;
      margin-top:-50px;
      margin-left:-50px;
      height:100px;
      width:100px;
      background: red;
    }
</style>
// 第二种办法
<div class="box2">
    <div class="inner">2</div>
</div>
<style>
    .box2{
      position:relative;
      height:100vh;
    }
    .inner{
      position:absolute;
      left:50%;
      top:50%;
      background: red;
      transform: translate(-50%,-50%);
    }
</style>
// 第三种办法
<div class="box3">
    <div class="inner">3</div>
</div>
<style>
   .box3{
      position:relative;
      height: 100px;
      background-color: antiquewhite;
    }
    .inner{
      position:absolute;
      width:100px;
      height:50px;
      top:0;
      left:0;
      right:0;
      bottom: 0;
      margin:auto;
      background: rebeccapurple;
    }
</style>
// 第四种办法
<style>
<div class="box4">
    <div class="inner">4</div>
 </div>
.box4{
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
// 第五种办法
<div class="box5">
    <div class="inner">5.1</div>
    <div class="inner">5.2</div>
</div>
<style>
.box5{
  display: table;
  width:100%;
}
.inner{display: table-cell;}
</style>
正文完
 0