登录
首页 >  文章 >  前端

如何让div居中?

来源:dev.to

时间:2024-07-11 12:45:56 196浏览 收藏

积累知识,胜过积蓄金银!毕竟在文章开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《如何让div居中?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

如何让div居中?

如何在 css 中将 div 居中

使div居中是最不可能的事情

1. 使用 flexbox 居中

flexbox 是一种垂直和水平居中内容的现代方式:

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>

2. 网格居中

css grid 还可以居中内容:

.container {
    display: grid;
    place-items: center;
    height: 100vh;
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>

3. 绝对定位居中

您可以使用绝对定位将 div 居中:

.container {
    position: relative;
    height: 100vh;
}
.centered-div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>

4. 使用 margin auto 居中

对于简单的水平居中,请使用 margin: auto:

.centered-div {
    width: 50%;
    margin: 0 auto;
}
<div class="centered-div">centered content</div>

5. 使用 margin auto 居中

对于内联或内联块元素:

.container {
    text-align: center;
    line-height: 100vh; /* full viewport height for vertical centering */
}
.centered-div {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>

到这里,我们也就讲完了《如何让div居中?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>