【Css】怎么实现水平垂直居中

62 阅读2分钟

在CSS中,实现元素的水平垂直居中可以通过多种方式完成,具体方法取决于你的布局需求和上下文环境。以下是一些常见的实现方式:

1. Flexbox

Flexbox布局是CSS3引入的一种布局模式,它提供了一种更加高效的方式来布局、对齐和分配容器中项目的空间,即使它们的大小未知或是动态变化的。

<div class="container">  
    <div class="child">我是居中的</div>  
</div>
.container {    
    height: 200px;  
    width: 200px;  
    display: flex; /* 使container成为flex容器 */  
    justify-content: center; /* 水平居中child */  
    align-items: center;     /* 垂直居中child */  
    background-color: skyblue;   
}    
.child {    
    height: 100px;  
    width: 100px;  
    display: flex;    
    justify-content: center; /* 水平居中child内的文本 */  
    align-items: center;     /* 垂直居中child内的文本 */  
    background-color: pink;  
    /* 如果child内只有文本,你可能不需要设置宽高,除非有特殊需求 */  
}  

2. Grid

Grid布局是另一种CSS布局方法,它基于网格概念来布局网页。

 .container {  
    height: 200px;  
    width: 200px;  
    background-color: skyblue;   
    display: grid;  
    place-items: center; /* 简写,同时实现水平和垂直居中 */  
}  
.child {  
    height: 100px;  
    width: 100px;  
    background-color: pink;  
}

3. 绝对定位 + 转换(Transform)

当你知道父元素的大小,或者父元素占满了整个视口时,可以使用绝对定位和转换来实现居中。

 .container {  
    height: 200px;  
    width: 200px;  
    background-color: skyblue;   
    position: relative;  
}  
.child {  
    position: absolute;  
    top: 50%;  
    left: 50%;  
    transform: translate(-50%, -50%);  
    height: 100px;
    width: 100px;  
    background-color: pink;  
}

4. 绝对定位 + 负边距

这种方法也依赖于你知道父元素的大小,并且子元素有一个固定的大小。

.container {  
    position: relative;  
    height: 200px;  
    width: 200px;  
    background-color: skyblue; 
}  
.child {  
    position: absolute;  
    top: 50%;  
    left: 50%;  
    margin-top: -50px; /* 高度的一半 */  
    margin-left: -50px; /* 宽度的一半 */  
    height: 100px;
    width: 100px;  
    background-color: pink;
}

5. 表格布局(不推荐,仅作了解)

虽然不常用,但你也可以通过表格布局来实现居中。这种方法更适用于较老的布局技术或特定情况。

.container {  
    display: table;  
    height: 200px;  
    width: 200px;  
    background-color: skyblue; 
    text-align: center; /* 水平居中 */  
    vertical-align: middle; /* 但这里不起作用,因为需要额外的单元格来应用此属性 */  
    display: table-cell;  
}  

.child {  
    display: inline-block;    
    height: 100px;
    width: 100px;  
    background-color: pink;
}