css 水平垂直居中

<div class="box">
    <div class="center">
         需要水平垂直居中的元素
     </div>
 </div>

1.flex 布局

<style>
        .box{
            width:200px;
            height: 300px;
            background-color:palegoldenrod;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .center{
            background-color: orange;
        }
    </style>

在这里插入图片描述

2.定位加transform

<style>
        .box{
            width:200px;
            height: 300px;
            background-color:palegoldenrod;
            position: relative;
        }
        .center{
            background-color: orange;
            position: absolute;
            top: 50%;
            left: 50%;
            right: 0;
            bottom:0;
            transform:translate(-50%,-50%)
        }
    </style>

在这里插入图片描述

3.父元素设置table,子元素利用table-cell,text-align

<style>
        .box{
            width:200px;
            height: 300px;
            background-color:palegoldenrod;
            display: table;
            //为了区分出父元素
            padding:10px;
        }
        .center{
            background-color: orange;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
    </style>

在这里插入图片描述

总结:

  1. 以上三种解法各自代表了css的布局、定位、display可设置的属性
  2. 子元素均不知高、宽
  3. 在定位上面还可以做不同的定位来实现