意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

CSS实现垂直水平居中有几种方法,哪种好

来源:恒创科技 编辑:恒创科技编辑部
2024-01-11 18:16:59
这篇文章主要介绍“CSS实现垂直水平居中有几种方法,哪种好”,有一些人在CSS实现垂直水平居中有几种方法,哪种好的问题上存在疑惑,接下来小编就给大家来介绍一下相关的内容,希望对大家解答有帮助,有这个方面学习需要的朋友就继续往下看吧。




CSS 居中对齐


CSS实现垂直水平居中有几种方法,哪种好

代码中均省略了浏览器前缀 以下例子以我的个人的标准排序 当然也有更多的居中处理方法 但我觉得只有这5种方法是最完善的解决方案

flex 居中

优点:可对未知高度进行居中处理

<style>
    .wrap{height: 100%;display: flex; justify-content: center; align-items: center;align-content:center;}
    
    .other{background-color: #ccc; width: 400px;height: 400px;} /* 额外的样式 可去除 */
</style>
<div class="wrap">
    <div class="other">
        <h2>这是第二层的内容 不会居中</h2>
    </div>
</div>

position + translate 居中

优点: 可对未知高度进行居中处理、嵌套层最少

<style>
    /* position 可选 absolute|fixed*/
    .center{position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);}
    
    .other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<div class="center other">
    <h2>这一层的内容 不会居中</h2>
</div>

table-cell 居中

缺点:1. 居中层需要设置宽度(.center)。 2.外层多嵌套一层(.cell) 3. 居中层必须设置宽度(允许 %)

<style>
    .wrap{display: table;width: 100%;height: 100%;}
    .cell{display: table-cell;vertical-align:middle;}
    .center{width: 400px;margin-left:auto;margin-right:auto;}
    .other{background-color: #ccc;  height: 400px;} /* 额外的样式 可去除 */
</style>
<div class="wrap">
    <div class="cell">
        <div class="center other">
            <h2>这一层的内容 不会居中</h2>
        </div>
    </div>
</div>

传统居中 (2种)

缺点:1. margin 值必须为auto。 2. 居中层必须设置高宽(允许 %) 3. 必须使用 position

<style>
    /*
        1. left、top、right、bottom 可以任意,但必须相等
        2. position 可选 absolute|fixed
    */
    .center{position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;margin: auto;width: 400px;height: 400px;}
    .other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<div class="center other">
    <h2>这一层的内容 不会居中</h2>
</div>

缺点: 居中层必须设置固定高宽,并且magin需要通过高宽计算得出。

<style>
    .wrap{position: relative;height: 100%;}
    .center{position: absolute;left: 50%;top: 50%; width: 400px;height: 300px; margin-left: -200px;margin-top: -150px;}
    .other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<div class="wrap">
    <div class="center other">
        <h2>这一层的内容 不会居中</h2>
    </div>
</div>

总结


这篇关于“CSS实现垂直水平居中有几种方法,哪种好”的文章就介绍到这了,更多相关的内容,欢迎关注群英网络,小编将为大家输出更多高质量的实用文章!
上一篇: CSS预处理器具备哪些功能,用法是怎样的 下一篇: 手机怎么远程登录云服务器?