垂直水平居中的方式

方式一:知道元素高度
  1. 给该元素设置绝对定位;
  2. 设置绝对定位元素的left:50%;,top:50%;
  3. 再设置绝对定位元素的 margin-left: -元素宽度的一半px;margin-top: -元素高度的一半px;
  4. 注意:如果只需要水平居中,只需要设置leftmargin-left的值;
    如果只需要垂直居中,只需要设置topmargin-top的值;
  5. 弊端:需要确切知道元素的宽度,只能为某一张图片设置,图片替换掉后,就不一定有效。
<div class="box1">
    <div class="box2"></div>
</div>

<style>
 .box2{
     background: #33AE75;
     width: 200px;
     height: 200px;
     position: absolute;
     top: 50%;
     left: 50%;
     margin-top: -100px;
     margin-left: -100px;
 }
</style>
方式二:不知道元素的高度
  1. 给该元素设置绝对定位;
  2. 给该元素设置margin: auto;
  3. left、top、bottom、right的值都为0。
<div class="box1">
    <div class="box2"></div>
</div>

<style>
 .box2{
     width: 200px;
     height: 200px;
     background: #b92c28;
     margin: auto;
     position: absolute;
     left: 0;
     top: 0;
     bottom: 0;
     right: 0;
 }
</style>
方式三:CSS3的相关属性
  1. 给该元素设置绝对定位;
  2. 设置top: 50%;left: 50%;
  3. 设置transform: translate(-50%,-50%);
<div class="box1">
    <div class="box2"></div>
</div>

<style>
 .box2{
     position: absolute;
     top: 50%;
     left: 50%;
     transform: translate(-50%,-50%);
     width: 200px;
     height: 200px;
     background: #8d66c6;
 }
</style>

水平居中:

left:50%; 
transform: translateX(-50%);

垂直居中:

top:50%; 
transform: translateY(-50%);

水平垂直居中:

left:50%; 
top:50%; 
transform: translate(-50%, -50%);
方式四:flex布局
  1. 设置容器为伸缩布局,并设置高度和宽度;
  2. 设置伸缩容器主轴对齐方式和侧轴对齐方式为center
<div class="box1">
    <div class="box2"></div>
</div>

<style>
  html,body{
     width: 100%;
     height: 100%;
  }
  .box1{
     display: flex;
     justify-content: center;
     align-items: center;
     width: 100%;
     height: 100%;
  }
  .box2{
     width: 100px;
     height: 100px;
     background: #000;
  }
</style>

垂直水平居中图片
  1. 给容器设置以下代码:
    //display: table-cell;
    //vertical-align: middle;
    //text-align: center;
<div class="box1">
    <img src="./../images/1.jpg" alt="">
</div>

<style>
  .box1{
     width: 500px;
     height: 500px;
     display: table-cell;
     vertical-align: middle;
     text-align: center;
     border: 1px solid #000;
  }
  .box1 img{
     width: 100px;
     height: 100px;
     background: #000;
  }
</style>
水平居中图片
  1. 需要配合text-align: center;使用,其父元素需要设置text-align: center;
  2. 给图片设置margin: 0 -100%;
<div class="box1">
    <img src="./../images/1.jpg" alt="">
</div>

<style>
  .box1{
     width: 400px;
     height: 400px;
     border: 10px solid red;
     margin: 50px auto;
     text-align: center;
  }
  .box1 img{
     margin: 0 -100%;
  }
</style>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。