css水平垂直居中

时间:2020-05-21
本文章向大家介绍css水平垂直居中,主要包括css水平垂直居中使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

块级元素居中

一、居中元素不定宽高情况(子元素有内容)

  • 关键样式父元素position: relative, 子元素position: absolute, 上左为50%,transform: translate(-50%, -50%)
<style>
    .main {
        background-color: aquamarine;
        width: 400px;
        height: 400px;

        /* 关键代码 */
        position: relative;
    }

    .content {
        background-color: red;

        /* 关键代码 */
        position: absolute;

        /* 垂直居中 */
        top: 50%;
        transform: translateY(-50%);

        /* 水平居中 */
        left: 50%;
        transform: translateX(-50%);

        /*transform: translate(-50%, -50%);*/
    }
</style>
  • flex, 父元素设置display: flex, align-items: center, justify-content: center.
<style>
    .main {
        background-color: aquamarine;
        width: 400px;
        height: 400px;

        /* 关键代码 */
        display: flex;

        /* 垂直居中 */
        align-items: center;

        /* 水平居中 */
        justify-content: center;
    }

    .content {
        background-color: red;
    }
</style>

二、仅居中元素定宽高情况

  • 关键样式父元素position: relative, 子元素position: absolute, 上下左右0,margin: auto
<style>
    .main {
        background-color: aquamarine;
        width: 400px;
        height: 400px;

        /* 关键代码 */
        position: relative;
    }

    .content {
        background-color: red;
        width: 200px;
        height: 200px;

        /* 关键代码 */
        position: absolute;

        /* 垂直居中 */
        top: 0;
        bottom: 0;

        /* 水平居中 */
        left: 0;
        right: 0;
        margin: auto;
    }
</style>

行内元素居中

  • 水平居中text-align: center
  • 垂直居中父height,子line-height同高

原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/12928683.html