CSS元素如何居中?

水平居中

1.内联元素(如span、img、button、a标签等)使用text-align: center;

.parent{
    text-align: center;
}

2.父元素中谁需要居中,就给其设置margin: 0 auto;使盒子自己居中

.child{
    width: 200px;
    height: 200px;
    border: 1px solid red;
    margin: 0 auto;
}

3.使用定位属性

.parent{
    position: relative;
}
.child{
    width: 200px;
    height: 200px;
    border: 1px solid red;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

4.使用flex

.parent{
    display: flex;
    justify-content: center;
}
.child{
    width: 200px;
    height: 200px;
    border: 1px solid red;
}
水平垂直居中

1.使用flex

.parent{
    height: 600px;
    border: 1px solid green;
    display: flex;
    justify-content: center;
    align-items: center;
}
.child{
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

2.使用定位属性(爸爸relative,儿子absolute)

.parent{
    height: 600px;
    border: 1px solid green;
    position: relative;
}
.child{
    width: 200px;
    height: 200px;
    border: 1px solid red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

3.使用margin: auto;

.parent{
    height: 600px;
    border: 1px solid green;
    position: relative;
}
.child{
    width: 200px;
    height: 200px;
    border: 1px solid red;
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
垂直居中

4.使用table自带的功能

.parent{
  border: 1px solid red;
  height: 600px;
}
.child{
  border: 1px solid green;
}

<table class="parent">
    <tr>
      <td class="child">
      一串文字一串文字一串文字一串文字一串文字
      </td>
    </tr>
</table>

5.div装成table

<div class="table">
    <div class="tr">
        <div class="td">一串文字一串文字一串文字一串文字一串文字
        </div>
    </div>
</div>
<style>
    div.table{
        display: table;
        border: 1px solid red;
        height: 600px;
    }
    div.tr{
        display: table-cell;
        border: 1px solid blue;
        vertical-align: middle;
    }
    .td{
        border: 1px solid black;
    }
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。