css设置元素居中总结

126 阅读1分钟

水平居中

块级元素

flex布局(设置在父元素)

display:flex;
justify-content:center;

grid布局(设置在父元素)

display:grid;
justify-content:center

水平居中和垂直居中同时设置

place-items: center;

绝对定位(设置在子元素)

position:absolute;
left:-50%;
//1.使用transform
transform: translate(-50%, 0);
//2.使用margin
margin-left:-width*50%

浮动元素水平居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .parent {
            margin: 0 auto;
            width: -moz-fit-content;
            width: -webkit-fit-content;
            width:fit-content;
        }
        .son{
            float: left;
            background: pink;
            width:50px;
            height:50px;
        }
    </style>
</head>
<body>
    <div class='parent'>
        <div class="son">

        </div>
    </div>
</body>
</html>

fit-content是CSS3中给width属性新加的一个属性值,它配合margin可以轻松实现水平居中, 目前只支持Chrome 和 Firefox浏览器

行内元素

父元素设置text-align:center

垂直居中

块级元素

flex布局(设置在父元素)

display:flex;
align-item:center;

grid布局(设置在父元素)

display:grid;
align-item:center;

水平居中和垂直居中同时设置

place-items: center;

绝对定位(设置在子元素)

position:absolute;
top:-50%;
//1.transform
transform:tranlate( 0, -50%);
//2.margin
margin-top:-height*50%

table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .parent {
            background: #ccc;

            display: table;
        }
        .son{
            background: pink;

            display: table-cell;
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <div class='parent'>
        <div class="son">123</div>
    </div>
</body>
</html>

使用 display: table; 可以模拟表格布局的特点,例如自动等分列宽和自动增长行高等。但与使用真正的HTML表格相比,使用 display: table; 具有更多的灵活性,因为它不会限制你只能使用特定的表格元素(如 <tr><td> 等),而是可以在任何元素上应用这些属性。

display: table-cell;: 将元素呈现为表格单元格。

display: table-row; 将元素呈现为表格行。

display: table-header-group;display: table-footer-group;: 将元素分别呈现为表格的页眉组和页脚组。

行内元素

height:50px;
line-height:50px;

行高与高度一致

本文由博客一文多发平台 OpenWrite 发布!