6 种让 div 居中的方法

2025-06-09

6 种让 div 居中的方法

是的,我知道我们都遇到过这种情况。我们想让 a 元素居中div,或者让其child位于父元素内部,但有时行不通,或者很难做到。所以现在,让我来介绍 6 种几乎适用div于所有情况的居中方法。

问题

我们有 2 个 divparentchild,我们需要将child其居中parent



<div class="parent">  
    <div class="child"></div>  
</div>


Enter fullscreen mode Exit fullscreen mode

目标 - 它应该看起来像这样

现在我们知道了我们想要实现的目标。那么让我们看看这个问题有哪些可能的解决方案。

1. 使用 Flexbox

灵活的盒子布局模块,可以更轻松地设计灵活的响应式布局结构。

应用以下属性.parent将水平和垂直居中.child



.parent {  
    display: flex;  
    justify-content: center;  
    align-items: center;  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

2. 使用位置

position属性指定元素使用的定位方法类型(静态、相对、固定、绝对或粘性)。我们只需要相对和绝对。

应用以下属性并将.parent水平和垂直.child居中。.child



.parent {  
    position: relative;  
}
.child {  
    position: absolute;  
    top: 50%;  
    left: 50%;  
    transform: translate(-50%, -50%);  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

3. 使用 CSS 网格

CSS 网格布局模块提供了一个基于网格的布局系统,有行和列。我们child也可以用它来将元素居中。

应用以下属性来.parent实现.child水平和垂直居中。



.parent {  
    display: grid;  
    justify-content: center; /* Horizontal */  
    align-content: center; /* Vertical */  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

另外还有另一种使用网格的方法,您可以将以下属性应用于.parent



/* Another Approach */
.parent {  
    display: grid;  
    place-items: center;  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

4. 在物品margin: auto使用flex

Flexbox 为边距引入了一项非常棒的功能auto。现在,它不仅能像块布局一样将元素水平居中,还能使其在垂直轴上居中。

应用以下属性来.parent实现.child水平和垂直居中。



.parent{ 
    display:flex; 
}  

.child { 
    margin:auto;  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

flex5.容器上的伪元素

虽然这不是世界上最实用的方法,但我们也可以使用灵活的空伪元素将元素推到中心。

应用以下属性来.parent实现.child水平和垂直居中。



.parent { 
    display: flex; 
    flex-direction: column;  
}  
.parent::before, 
.parent::after { 
    content:  ""; 
    flex:  1;  
}  
.child {  
    /* ...other CSS */ 
    margin: 0 auto;  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

6.margin: auto关于某件grid物品

与 Flexbox 类似,应用到项目margin: autogrid会使其在两个轴上居中。



.parent { 
    display: grid;  
}  
.child { 
    margin:  auto;  
}


Enter fullscreen mode Exit fullscreen mode

代码笔

结论

这些并非唯一的解决方案,也不是让孩子集中注意力的唯一方法。还有很多其他方法可以达到同样的效果,但我只知道这些,所以分享给大家。如果你还有其他方法,欢迎留言分享。

现在您可以通过给我买一杯咖啡来表示您的支持。😊👇

给我买杯咖啡

另请阅读

鏂囩珷鏉ユ簮锛�https://dev.to/j471n/6-ways-to-center-a-div-5fgj
PREV
2022 年 11 月 Chrome 扩展程序月度推荐
NEXT
2023 年 10 大最佳开发者礼品