在 CSS 中将 div 居中的 3 种方法

2025-05-24

在 CSS 中将 div 居中的 3 种方法

在 HTML/CSS 中将 div 居中的 3 种方法!!

带位置

/* Using positions */

.parent {
    position: relative;
}
.child {
    left: 50%;
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode
<div
     class="parent"
     style="background: blue; width: 500px; height: 250px;"
     >
    <div
         class="child"
         style="color: white;"
         >
      I'm center  
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

使用 Flexbox

/* Using flexbox */
.container-flexbox {
    align-items: center;
    display: flex;
    justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode
<div
     class="container-flexbox"
     style="background: green; width: 500px; height: 250px;"
     >
    <div
         style="color: white;"
         >
      I'm center  
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

带网格

/* Using Grid */

.container-grid {
    display: grid;
    place-content: center;
}

Enter fullscreen mode Exit fullscreen mode
<div
     class="container-flexbox"
     style="background: orange; width: 500px; height: 250px;"
     >
    <div
         style="color: white;"
         >
      I'm center  
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode


我希望你喜欢这篇文章!

🎁 如果您在Twitter上关注我并给我发送消息,您可以Underrated skills in javascript, make the difference免费获得我的新书😁 并节省 19 美元💵💵

或者在这里获取

🇫🇷🥖 对于法国开发者,你可以查看我的YoutubeChannel

🎁我的新闻通讯

☕️ 你可以支持我的作品🙏

🏃‍♂️ 你可以关注我 👇

🕊 推特:https://twitter.com/code__oz

👨‍💻 Github:https://github.com/Code-Oz

你也可以标记🔖这篇文章!

文章来源:https://dev.to/codeoz/3-ways-to-center-a-div-in-css-gl1
PREV
6 Repos github 您应该标记为 web 开发人员!
NEXT
关于 JavaScript 中的 Promises