欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

css居中对齐的几种方式

程序员文章站 2022-04-26 15:57:58
...

第一种

css

.parent {
            width: 300px;
            height: 300px;
            background: #fff000;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
}
        
.child {
            display: inline-block;
            /* 水平居中对齐 */
            margin: auto;
            border: 1px solid red;
}

html

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

第二种

css

.parent {
            position: relative;
            height: 200px;
            width: 200px;
            border: 1px solid red;
        }
        
        .child {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

html

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

第三种

css

.parent {
            width: 300px;
            height: 300px;
            background: #ddd;
            position: relative;
        }
        
        .child {
            width: 200px;
            height: 100px;
            background-color: #a0c8ff;
            position: absolute;
            /*竖直方向居中*/
            top: 0;
            bottom: 0;
            /*水平方向居中*/
            left: 0;
            right: 0;
            margin: auto;
            line-height: 100px;
        }

html

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

第四种

css

.parent {
			height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid red;
        }

html

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